c++ - 将指针的类型作为模板参数传递

标签 c++ templates pointers

我会用一个例子来解释:

template<typename T>
class Base{}

class A: public Base<A>{}

class foo(){
public:
   template<typename T>
   bool is_derived(){
      /* static check if T is derived from Base<T> */
   }
}

我找到了 this特征来确定一个类是否是另一个类的基础。

我的问题是,如果 T 是一个指针而不专门化 boo 模板函数,我如何将模板参数从 T 发送到 is_base_of?

我想做这样的事情: 如果 T 是一个指针那么 if (is_base_of<Base<*T>,*T>) return true; 如果 T 不是指针则 if (is_base_of<Base<T>,T>) return true;

最佳答案

你可以使用 std::remove_pointer traits:

class foo(){
public:
   template<typename T>
   bool is_derived() const {
      using type = std::remove_pointer_t<T>;
      static_assert(std::is_base_of<Base<type>, type>::value,
                    "type should inherit from Base<type>");
   }
};

关于c++ - 将指针的类型作为模板参数传递,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37956299/

相关文章:

c++ - 段错误 - 读取初始化指针数组

c++ - 有没有办法通过从另一个文件读取值来为宏赋值?

模板的 C++ 链接错误,仅使用头文件,为什么?

c++ - 如何定义模板类的模板

c++ - 带有模板参数的函数指针

C++ 用空格分割一个字符串,除非它被引号括起来并存储在一个 vector 中

c++ - 将秒数转换为时间

python - Django 找不到模板

c - C语言中指针交换时使用整数声明而不是指针整数

C结构内存管理