C++17更新:
使用C++17的折叠表达式,这几乎变得非常简单:
template <typename Type, typename... Requirements>
class CommonBase
{
static_assert((std::is_base_of_v<Type, Requirements> && ...), "Invalid.");
};
你可以使用展开语法和一些静态版本的std::all_of来实现(C++11/14):
template <bool... b> struct static_all_of;
template <bool... tail>
struct static_all_of<true, tail...> : static_all_of<tail...> {};
template <bool... tail>
struct static_all_of<false, tail...> : std::false_type {};
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.");
};
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
的问号所得到的值列表。也就是说,对于main函数中的第一行,它将扩展为static_all_of<true, true>,对于第二行,则为static_all_of<true, false, true>。
is_base_of<Requirements...>::value
没有提到第二个参数。 - iammilindstatic_assertion
是编译时的过程(参见这里)。编译器会在编译时检查is_base_of
的值吗? - Amir Naghizadehis_base_of
本身就是一个模板,而模板在编译时被实例化。 - Arne Mertz