爲C++ 17更新: 用C++ 17的摺疊表達式這變得幾乎微不足道:
template <typename Type, typename... Requirements>
class CommonBase
{
static_assert(std::is_base_of_v<Type, Requirements> && ..., "Invalid.");
};
原來的答案(C++ 11/14): 您可以使用包擴展和一些靜態版本std::all_of
:
template <bool... b> struct static_all_of;
//implementation: recurse, if the first argument is true
template <bool... tail>
struct static_all_of<true, tail...> : static_all_of<tail...> {};
//end recursion if first argument is false -
template <bool... tail>
struct static_all_of<false, tail...> : std::false_type {};
// - or if no more arguments
template <> struct static_all_of<> : std::true_type {};
template <typename Type, typename... Requirements>
class CommonBase
{
static_assert(static_all_of<std::is_base_of<Type, Requirements>::value...>::value, "Invalid.");
// pack expansion: ^^^
};
struct Base {};
struct Derived1 : Base {};
struct Derived2 : Base {};
struct NotDerived {};
int main()
{
CommonBase <Base, Derived1, Derived2> ok;
CommonBase <Base, Derived1, NotDerived, Derived2> error;
}
該包的擴展將擴展到值,您在Requirements...
將每一種類型爲std::is_base_of<Type, ?>::value
問號,即在主要的一線得到的名單將擴大到static_all_of<true, true>
,第二線將是static_all_of<true, false, true>
我懷疑這是可能的。你的第一個'is_base_of :: value'也沒有提到第二個參數。 –
iammilind
'static_assertion'是編譯時過程([here](http://stackoverflow.com/questions/1647895/what-does-static-assert-do-and-what-would-you-use-it-for))編譯時檢查'is_base_of'值嗎? –
@tAmirNaghizadeh當然它確實如此,因爲'is_base_of'本身就是一個模板,並且模板在編譯時被實例化。 –