我想要一个类似于下面的模板类。然后,我希望其中有一个函数,该函数具有依赖于 CLASS 模板参数的模板特化。我如何使这项工作?我意识到我提供的代码在很多层面上都是错误的,但这只是为了说明这个概念。
template <typename _T, size_t num>
class Foo
{
// If num == 1, I want to call this function...
void Func<_T, 1>()
{
printf("Hi!");
}
// Otherwise, I want to call this version.
void Func<_T, num>()
{
printf("Hello world!");
}
};
最佳答案
struct Otherwise { };
template<size_t> struct C : Otherwise { };
// don't use _Uppercase - those names are reserved for the implementation
// (i removed the '_' char)
template <typename T, size_t num>
class Foo
{
public:
void Func() { Func(C<num>()); }
private:
// If num == 1, I want to call this function...
void Func(C<1>)
{
printf("Hi 1!");
}
// If num == 2, I want to call this function...
void Func(C<2>)
{
printf("Hi 2!");
}
// Otherwise, I want to call this version.
void Func(Otherwise)
{
printf("Hello world!");
}
//// alternative otherwise solution:
// template<size_t I>
// void Func(C<I>) { .. }
};
关于c++ - 模板类,函数特化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2349995/