假设你有:
template<class T>
class A {
template<class T1>
void foo(const T1& t1) {}
//
// Lots of other definitions (all templated)
//
};
并且您希望专注foo(const T1&)
,但仅适用于专门的A<bool>
。像这样:
template<>
class A<bool> {
template<class T1>
void foo(const T1& t1) {
// Code for specialized A<boo>::foo
}
//
// Repeating the former definitions, how to avoid this ??
//
};
但要实现这一点,我必须复制在类模板class A
中定义的所有代码,并将其再次包含在class A<bool>
中。
我试图只定义成员专业化:
template<>
void A<bool>::template<class T1> foo(const T1&) {}
这两项都不起作用:
template <class T1> void A<bool>::foo(const T1&) {}
但是编译器不喜欢它。 处理此代码重复的方法是什么?
答案 0 :(得分:7)
答案 1 :(得分:0)
您可以提供函数和类模板,然后定义几个typedef:
template<class T, class TArg>
class A
{
void foo(const TArg& arg) {}
// Lots of other definitions (all templated)
};
typedef A<MyType, MyType> NormalClass;
typedef A<MyType, bool> BoolClass;