可能很容易解决,但很难找到解决方案:
是否有可能(部分地)特化一整套类型? 在示例中,“Foo”应该部分特化为 (T,int) 和 (T,double),只有一个模板定义。
我能做的是为 (T,int) 定义一个特化。见下文。但是,它应该用于 (T,int) 和 (T,double) 只有一个函数定义(没有代码加倍)。
template <typename T,typename T2>
struct Foo
{
static inline void apply(T a, T2 b)
{
cout << "we are in the generic template definition" << endl;
}
};
// partial (T,*)
template <typename T>
struct Foo<T, int > // here something needed like T2=(int, double)
{
static inline void apply(T a, T2 b)
{
cout << "we are in the partial specialisation for (T,int)" << endl;
}
};
关于如何使用一个模板定义为 (T,int) 和 (T,double) 部分特化它有什么想法吗?
最佳答案
如果我正确理解你的问题,那么你可以编写一个基类模板并从中派生,如下所示:
template <typename T, typename U>
struct Foo_Base
{
static inline void apply(T a)
{
cout << "we are in the partial specialisation Foo_Base(T)" << endl;
}
};
template <typename T>
struct Foo<T, int> : Foo_Base<T, int> {};
template <typename T>
struct Foo<T, double> : Foo_Base<T, double> {};
虽然它不是一个模板定义(如您所要求的),但您可以避免代码重复。
关于c++ - 一整套参数的模板特化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5694843/