c++ - 带有指针模板参数的模板类的特化

标签 c++ templates pointers template-specialization

我想为多个指向不同对象的指针专门设计一个模板类。对于普通指针来说,这按预期工作:

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/

相关文章:

c++ - 链表中的唯一指针 - 未处理的异常,堆栈溢出

C - 将数组引用传递给函数中的指针参数时遇到问题

c++ - Arduino Nano:使用串行输入时,通过计时器进行的A4988步进控制不稳定

c++ - 使用 Boost Spirit Qi 解析分隔的 token 列表

c++ - 使用 MapViewOfFile 映射大文件

c++ - 我应该专攻还是重载?

c++ - 为什么我不能在赋值的右侧放置一个指向 const 的指针?

c++ - 如何将多个字符组合成一个字符串?

wpf - 提取正在运行的WPF应用程序的WPF内容模板

c++ - 如何使用 C++ 模板模拟类型引用?