我找到了破解系统的方法。使用部分特化而不是显式特化,使用伪模板参数,例如:http://goo.gl/yHRQwV
template <typename T1>
class A
{
public:
template <bool T2, typename = void>
class B;
template <typename Dummy>
class B<true, Dummy>
{
public:
void f1();
};
template <typename Dummy>
class B<false, Dummy>
{
public:
void f1();
};
};
template <typename T1>
template <typename Dummy>
void A<T1>::B<true, Dummy>::f1()
{
}
template <typename T1>
template <typename Dummy>
void A<T1>::B<false, Dummy>::f1()
{
}
int main()
{
A<int>::B<true> b1;
b1.f1();
A<int>::B<false> b2;
b2.f1();
}
不确定这是否合法,但它有效。
实际上,它并没有解决我的问题。在这种情况下,我无法在没有专门化的情况下将通用方法 f2()、f3() 等添加到 B 类:http://goo.gl/wtIY0e
template <typename T1>
class A
{
public:
template <bool T2, typename = void>
class B
{
public:
void f2();
void f3();
};
template <typename Dummy>
class B<true, Dummy>
{
public:
void f1();
};
template <typename Dummy>
class B<false, Dummy>
{
public:
void f1();
};
};
template <typename T1>
template <typename Dummy>
void A<T1>::B<true, Dummy>::f1()
{
}
template <typename T1>
template <typename Dummy>
void A<T1>::B<false, Dummy>::f1()
{
}
template <typename T1>
template <bool T2, typename Dummy>
void A<T1>::B<T2, Dummy>::f2()
{
}
template <typename T1>
template <bool T2, typename Dummy>
void A<T1>::B<T2, Dummy>::f3()
{
}
int main()
{
A<int>::B<true> b1;
b1.f1();
b1.f2(); // error: A<int>::B<true> has no member f2
b1.f3(); // error: A<int>::B<true> has no member f3
A<int>::B<false> b2;
b2.f1();
b2.f2(); // error: A<int>::B<false> has no member f2
b2.f3(); // error: A<int>::B<false> has no member f3
}
终于找到了找了一整天的解决方案:静态多态http://goo.gl/7yGZxM
template <typename T1>
struct A
{
template<typename T2>
struct BaseB
{
void f1();
void f2();
void f3();
};
struct B_true : BaseB<B_true>
{
void f1_impl();
};
struct B_false : BaseB<B_false>
{
void f1_impl();
};
};
template <typename T1>
template<typename T2>
void A<T1>::BaseB<T2>::f1()
{
static_cast<T2*>(this)->f1_impl();
}
template <typename T1>
template<typename T2>
void A<T1>::BaseB<T2>::f2()
{
}
template <typename T1>
template<typename T2>
void A<T1>::BaseB<T2>::f3()
{
}
template <typename T1>
void A<T1>::B_true::f1_impl()
{
}
template <typename T1>
void A<T1>::B_false::f1_impl()
{
}
int main()
{
A<char>::B_true b_true;
b_true.f1();
b_true.f2();
b_true.f3();
A<char>::B_false b_false;
b_false.f1();
b_false.f2();
b_false.f3();
}