【发布时间】:2018-03-20 02:04:12
【问题描述】:
我有 2 个遵循类似模式的课程:
Foo.h
// header guard here
class Foo {
public:
Foo() = delete;
static foo1& getFoo1( Param a, Param b, Param c ) {
// code...
}
static foo2& getFoo2( Param a, Param b, Param c ) {
// code...
}
// generic function to return appropriate Foo Type based on template argument
template<class FooType>
static FooType& getFoo( Param a, Param b, Param c );
};
#endif
Foo.cpp
#include <Foo.h>
// specializations of getFoo() for each type
template<>
foo1& Foo::getFoo( Param a, Param b, Param c ) {
return getFoo1( a, b, c );
}
template<>
foo2& Foo::getFoo( Param a, Param b, Param c ) {
return getFoo2( a, b, c );
}
上面的 Foo 编译得很好。另一方面,Bar 具有与上述Foo 相似的结构或模式;唯一的区别是它是静态的getBar1()、getBar2() 等不仅仅是普通功能;它们是函数模板。
Bar.h
// header guard
class Bar {
public:
Bar() = delete;
template<class IntType = int>
static bar1<IntType>& getBar1( IntType a, IntType b ) {
// code...
}
template<class RealType = double>
static bar2<RealType>& getBar2( RealType a, RealType b ) {
// code...
}
template<class IntType = int>
static bar3<IntType>& getBar3( IntType a ) {
// code...
}
template<class RealType = double>
static bar4<RealType>& getBar4( RealType a ) {
// code...
}
// ...
template<class RealType = double>
static bar12<RealType>& getBar12() {
// code...
}
template<class RealType = double, class A, class B>
static bar12&<RealType>& getBar12( A a1, A a2, B b1 ) {
// code...
}
template<class RealType = double, class X>
static bar12&<RealType>& getBar12( std::initialize_list<double> list, X x ) {
// code...
}
template<class RealType = double, class X>
static bar12&<RealType>& getBar12( std::size_t size, RealType a, RealType b, X x ) {
// code..
}
// Here is where I start to get into problems:
// I'm trying to do something similar to what I've done above in Foo for a generic function template.
template<typename Type, template<typename> class BarType, class... FuncParams>
static BarType<Type>& getBar( FuncParams... params );
};
#endif
Bar.cpp
#include "Bar.h"
// specializations of getBar() for each type
template<typename Type, class... FuncParams>
bar1<Type>& Bar::getBar( FuncParams... params ) {
return getBar1( params... );
}
template<typename Type, class... FuncParms>
bar2<Type>& Bar::getBar( FuncParams... params ) {
return getBar2( params... );
}
为什么当我开始添加一个类类型时,它是一个类模板;一切似乎都破裂了。上面的第一个类编译并返回适当的Foo。但是,在第二类 Bar 中,我不断收到编译器错误,即函数定义与现有声明不匹配。
这个问题与这里的这个问题有关:Specializing and or Overloading member function templates with variadic parameters
这个问题专门关于为什么一个编译而另一个不编译。
【问题讨论】:
标签: c++ c++11 templates variadic-templates partial-specialization