gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-10-31 02:18:24 26 4
gpt4 key购买 nike

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

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 中代码的链接。

最佳答案

如果您愿意稍微更改模板参数,这是可能的:

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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com