2014-05-23 97 views
2

的我有這樣一個類:檢查模板參數等於基類另一個模板參數

template <class T1, class T2> 
class A 
{ 
    //Error if Base class of T2 is not T1 (At compile time) 
}; 

我要檢查,如果T1是基類的T2。編譯時可以嗎?

一些例子:

class C{}; 
class B :public C{}; 

A< C, B > a;  //Ok because C is base class of B 
A<B, C> b;  //Error B is not base class of C 
A<char, char> c; //Error char is not base class of char 
//..... 
+3

http://en.cppreference.com/w/cpp/types/is_base_of + http://en.cppreference.com/w/ cpp/language/static_assert –

回答

7

std::is_base_of將讓你大部分的在那裏,但它不是qui你想要什麼。如果兩種類型相同,您還需要出錯,對於任何用戶定義類型Tis_base_of<T, T>::value始終爲true。結合檢查與std::is_same以獲得您想要的行爲。

template <class T1, class T2> 
class A 
{ 
    static_assert(std::is_base_of<T1, T2>::value && 
        !std::is_same<T1, T2>::value, 
        "T1 must be a base class of T2"); 
}; 

這將導致如下:

A< C, B > a;  //Ok because C is base class of B 
A<B, C> b;  //Error B is not base class of C 
A<char, char> c; //Error char is not base class of char 
A<B, B> d;  //Error B is not base class of B <-- this won't fail without 
       //         the is_same check 
+0

+1不知道。 :) – 0x499602D2

4

使用std::is_base_ofstd::enable_if

template < 
    class T1, 
    class T2, 
    class = typename std::enable_if< 
     std::is_base_of<T1, T2>::value 
    >::type 
> 
class A 
{ 
}; 

您還可以使用static_assert自定義消息:

template <class T1, class T2> 
class A 
{ 
    static_assert(std::is_base_of<T1, T2>::value, 
        "T1 must be a base class of T2"); 
}; 
相關問題