在下面的类模板中,我们可以将成员 Foo::Bar()
专门化为某种类型,例如 T
= int
:
template <typename T>
class Foo
{
public:
void Bar()
{
std::cout << "generic Bar()" << std::endl;
}
};
template<>
void Foo<int>::Bar()
{
std::cout << "specialized Bar()" << std::endl;
}
int main()
{
Foo<char> generic_foo;
Foo<int> specialized_foo;
generic_foo.Bar();
specialized_foo.Bar();
return 0;
}
如果 Foo 类有多个模板参数,我们如何做同样的事情:
template <typename T, int N>
class Foo
{
public:
void Bar()
{
std::cout << "generic Bar()" << std::endl;
}
};
// How can we specialize Foo::Bar() for T = int?
int main()
{
Foo<char, 0> generic_foo;
Foo<int, 0> specialized_foo;
generic_foo.Bar();
specialized_foo.Bar();
return 0;
}
我尝试了几种替代方法来专门针对 T
= int
来专门化 Foo::Bar()
,包括:
template<int N>
void Foo<int, N>::Bar()
{
std::cout << "specialized Bar()" << std::endl;
}
但是编译器全部拒绝了它们。
最佳答案
模板函数没有部分特化。您应该专门化class
。
template<int N>
class Foo<int, N>
{
public:
void Bar()
{
std::cout << "specialized Bar()" << std::endl;
}
};
关于c++ - 当类有多个模板参数时专门化成员模板?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24505001/