我想为多个指向不同对象的指针专门设计一个模板类。对于普通指针来说,这按预期工作:
struct Base{} b;
template<Base* B> struct Test{};
template<> struct Test<&b>{};
但不适用于指向派生
对象的指针:
struct Derived : Base{} d;
template<> struct Test<&d>{};
coliru 编译器(我认为它的 gcc 5.2
)显示以下错误:
main.cpp:14:26: error: could not convert template argument '& d' to 'Base*'
template<> struct Test<&d>{};
我不知道为什么不允许这样做,并且想知道是否有解决该问题的方法...
Here是 coliru 中代码的链接。
最佳答案
如果您愿意稍微更改模板参数,这是可能的:
struct Base {} b;
struct Derived : Base {} d;
struct A {} a;
template <class T, T *B,
class = std::enable_if_t<std::is_base_of<Base, T>::value>>
struct Test {};
template <> struct Test<Base, &b> {}; // OK
template <> struct Test<Derived, &d> {}; // OK
template <> struct Test<A, &a> {}; // compile error
关于c++ - 带有指针模板参数的模板类的特化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34537388/