方法3:
template
struct Base
{
//other function
//…
void Func()
{
#if B!=16
cout 《 "primary function" 《 endl;
#else
cout 《 "specialization function" 《 endl;
#endif
}
};
点评: 试图通过预编译来实现,但是这个方法是错误的。C++(www.cppentry.com)模板编译包括预编译,语法检查,模板实例化等阶段,在预编译阶段模板参数都还没有实例化呢。
方法4:
template
struct Base
{
//other function
//…
template
struct FuncObj
{
void operator()()
{
cout《"primary function"<
}
};
template<>
struct FuncObj<16>
{
void operator()()
{
cout《"specialization function"<
}
};
FuncObj Func;
};
点评: 通过成员类以防函数的形式特化, 增加了类成员变量。
方法5:
template
struct Base
{
//other function
//…
template
void FuncImpl()
{
cout《"primary function"<
}
template<>
void FuncImpl<16>()
{
cout《"specialization function"<
}
void Func()
{
FuncImpl();
}
};
点评:通过类成员模板函数特化来实现。
方法6:
template
struct Base
{
//other function
//…
template
class Int2Type
{
enum { value = N };
};
template
void FuncImpl(const Int2Type)
{
cout《"primary function"<
}
void FuncImpl(const Int2Type<16>)
{
cout《"specialization function"<
}
void Func()
{
FuncImpl(Int2Type());
}
};
点评: 通过将int根据值的不同转成不同的类型,然后通过函数重载实现。
方法7:
namespace
{
template struct conditional { typedef T type; };
template struct conditional {typedef U type; };
}
template
struct Base
{
//other function
//…
void Func ()
{
typedef typename ::conditional::type type;
Func_impl(type());
}
private:
struct primary_t { };
struct spec_t { };
void Func_impl (primary_t) { std::cout 《 "primary function" 《 std::endl; }
void Func_impl (spec_t ) { std::cout 《 "specialization function" 《 std::endl; }
};
点评: 和方法6类似,通过函数重载实现
方法8:
namespace
{
template struct enable_if { typedef T type; };
template struct enable_if {};
}
template
struct Base
{
//other function
//…
template
typename ::enable_if<16!=N>::type
FuncImpl () { std::cout 《 "primary function" 《 std::endl; }
template
typename ::enable_if<16==N>::type
FuncImpl () { std::cout 《 "specialization function" 《 std::endl; }
void Func() {
FuncImpl();
}
};
点评:通过enable_if, 利用SFINAE实现。
我们可以看到根据编译时模板参数int值的不同,我们重写模板类的某个成员函数的方法是多种多样的。针对上面这种情况,个人其实最推荐方法2,我们没必要把简单的问题复杂化。
下面我们考虑另外一个需求, 当模板类的某个参数是某种类型时, 我们要求特化其中的一个成员函数:
template
struct Base
{
//other function
//…
void Func(){ cout 《 "primary function" 《 endl; }
};
void test2()
{
Base a;
a.Func();
Base b;
b.Func();
}
int main()
{
test2();
}
要求上面的模板类如果T2 是string类型, 我们要求对Func特殊重写,其他的成员函数无论什么情况实现都是一样的。