我想专门针对不同对象的几个指针的模板类。这符合正常指针的预期效果:
struct Base{} b;
template<Base* B> struct Test{};
template<> struct Test<&b>{};
但不是指向Derived
个对象的指针:
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中代码的链接。
答案 0 :(得分:2)
如果您愿意稍微更改模板参数,则可以:
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
答案 1 :(得分:0)
您可以为所有类型(如果相关)定义通用模板,并为指针类型定义部分特化:
template <typename T>
struct MyTest { // generic implementation for all types
MyTest() { // here I make it unrelevant
static_assert(is_pointer<T>::value , "this class must be used with a pointer");
}
};
template <typename T>
struct MyTest<T*> { // partial specialisation for pointer types
MyTest() {
cout <<"generic implementation"<<endl;
}
};
您可以根据需要定义更多专精:
struct Base {};
struct Derived : Base {};
template <>
struct MyTest<Base*> { // specialisation for Base
MyTest() {
cout <<"specialized implementation for Base"<<endl;
}
};
template <>
struct MyTest<Derived*> { // specialisation for Derived
MyTest() {
cout <<"specialized implementation for Derived"<<endl;
}
};
在这里你可以如何使用它:
MyTest<Base> mt1; //<== faills because Base is not a poiner
MyTest<int*> mt0; // generic template
MyTest<Base*> mt2; // Base specialisation
MyTest<Derived*> mt3; // derived specialisation
这是online demo。