2016-06-21 110 views
0

我將在一個例子來解釋:傳遞指針的類型作爲模板參數

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

的std :: is_base_of :: type> –

+0

或者簡單的'std :: is_ba se_of >'in C++ 14。 –

+0

它可以是基地還是必須是基地? – Loay

回答

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

謝謝,那爲我解決了。在一個側面說明,爲什麼我不能做type = std :: remove_pointer_t ; 「使用關鍵字指示什麼?」 – Loay

+0

它是'typedef std :: remove_pointer_t 類型的C++ 11'typedef'語法;' – Jarod42

+0

沒有這個快捷方式,你必須寫'std :: is_base_of >,std :: remove_pointer_t > :: value' – Jarod42

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); 
} 
+0

您忘記了':: value',static_assert的第二個參數(至少對於C++ 11),並且'static_assert'在C++ 03。 – Jarod42

+0

@ Jarod42糾正了這一點。謝謝。 –

相關問題