将指针类型作为模板参数传递

时间:2016-06-21 23:41:16

标签: 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;

2 个答案:

答案 0 :(得分:1)

您可以使用std::remove_pointer特征:

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>");
   }
};

答案 1 :(得分:0)

基本上你已经回答了自己。

C ++ 14

bool is_derived(){
    static_assert( std::is_base_of<Base<T>, std::remove_pointer_t<T>>::value );
}

C ++ 11

bool is_derived(){
    static_assert( std::is_base_of<Base<T>, typename std::remove_pointer<T>::type>::value );
}

C ++ 03 - 你提到的is_base_of封装器(使用Boost.StaticAssert

template<class Base, class Derived> struct my_is_base_of : is_base_of<Base, Derived> { };
template<class Base, class Derived> struct my_is_base_of<Base*, Derived*> : is_base_of<Base, Derived> { };

// ...

bool is_derived(){
    BOOST_STATIC_ASSERT( my_is_base_of<Base<T>, T>::value );
}