实际上,您的特化是非特化,因为它不特化任何主模板的参数:
template<int A, int B>
struct S<A,B> // ...
// ^^^
// Does not really specialize the primary template,
// no specialized pattern is introduced here
您可以尝试这样重写它:
template<int A> // <== Only the first template parameter of the primary
// template is unconstrained in the pattern we want to
// express (the second template argument shall be 1)
struct S<A,1> : public S<A,0>
// ^^^ ^
// Specializes! Something meaningful should go here,
// but that actually depends on the real
// class templates you are using and their
// semantics
{
void fun1() {}
};
作为替代方案,如果您的目标只是有条件地添加一个成员函数,则可以使用如下所示的 SFINAE 约束而不是专门化:
#include <type_traits> // <== Required for std::enable_if<>
template <class T = void>
// ^^^^
// The function's return type here
typename std::enable_if<B == 1, T>::type
// ^^^^^^
// Your condition for the function's existence
fun1()
{
// ...
}
这是一个演示此技术的实时示例。