我有一个继承自另一个模板的模板,它本身就是第二个模板的模板参数。继承的模板定义了一个静态函数:
template<class T> class A
{
public:
static void foo();
};
template<class T> class B : public A<B>
{
};
现在我想为B专用的A类实现静态函数,但B不是专用的。但我无法弄清楚如何声明模板。我甚至不确定这是否可行。我的第一次尝试是:
template<class T> void A<B<T>>::foo()
{
}
但这会产生错误:
"Nested name specifier 'A<B<T>>::" for declaration does not refer into a class, class template or class template partial specialization"
我尝试过添加“template&lt;&gt;”等不同的功能在前面,但没有一个工作。我能够编译这个:
template<> void A<B<int>>::foo()
{
}
以及:
template<class T> void A<T>::foo()
{
}
这是部分专业化的尝试吗?我的第一印象是没有(没有带有多个参数的模板,我想专门研究其中一个参数)。相反,我想专门化一个模板与另一个非专业的模板。这是可能的,如果是这样,那么正确的语法是什么?
答案 0 :(得分:0)
这确实是部分专业化。您不能仅仅部分专门化一个方法,您必须部分专门化整个类。见this answer。您可以尝试在单独的帮助器结构中实现foo,而不是部分地专门化该结构。
以下是使用辅助结构的示例。
#include <iostream>
template<class T> struct t_helper
{
static void foo()
{
std::cout << "Not B<T>\n";
}
};
template<class T> class A
{
public:
static void foo() {
t_helper<T>::foo();
}
};
template<class T> class B {};
// Specialize the behavior of A<T>::foo() for all B types
template<class T>
struct t_helper<B<T>>
{
static void foo()
{
std::cout << "Is B<T>\n";
}
};
int main()
{
A<int>::foo(); // Prints "Not B<T>\n"
A<B<int>>::foo(); // Prints "Is B<T>\n"
return 0;
}