C++ 参数包感知std::is_base_of()

C++ 参数包感知std::is_base_of(),c++,templates,variadic-templates,typetraits,C++,Templates,Variadic Templates,Typetraits,是否有可能存在静态断言,以模板参数形式提供的类型是否实现参数包中列出的所有类型,即参数包感知std::Is_base_of() 模板 类公共基 { static_assert(是::value的_base_,“无效”); ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ std::is_base_of()的参数包感知版本 公众: 模板T*as() { static_assert(std::is_base_of::value,“Invalid”); 返回重新解释(本); } }

是否有可能存在静态断言,以模板参数形式提供的类型是否实现参数包中列出的所有类型,即参数包感知std::Is_base_of()

模板
类公共基
{
static_assert(是::value的_base_,“无效”);
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
std::is_base_of()的参数包感知版本
公众:
模板T*as()
{
static_assert(std::is_base_of::value,“Invalid”);
返回重新解释(本);
}
};

C++17的更新: 对于C++17的折叠表达式,这几乎变得微不足道:

template <typename Type, typename... Requirements>
class CommonBase
{
    static_assert((std::is_base_of_v<Type, Requirements> && ...), "Invalid.");
};

包扩展将扩展到通过在
Requirements…
中为
std::is_base_of::value
中的问号插入每种类型而获得的值列表,即对于main中的第一行,它将扩展到
static_all of
,对于第二行,它将是
static_all of
,仅供将来参考,因为我刚刚遇到了这个问题,使用C++17,您现在可以使用如下折叠表达式:

template<typename Base, typename... Args>
constexpr auto all_base_of()
{
    return (std::is_base_of<Base, Args>::value && ...);
}

static_assert(all_base_of<Base, A, B, C>());
模板
constexpr auto all_base_of()
{
返回(std::is_base of::value&&;
}
静态断言(all_base_of());

我怀疑这是否可能。另外,您的第一个
is_base_of::value
没有提到第二个参数。
静态断言是编译时进程(),编译器在编译时检查
is_base_of
value吗?@tAmirNaghizadeh当然会,因为
is_base_of
本身就是一个模板,我认为括号是必需的
static_assert((std::is_base_of_v&&…,“Invalid”)我的意思是在“用于C++17的Updae”代码中,而不是在原始代码中answer@Tarquiscani我的坏毛病,现在修好了。(并且了解到MSVC无论如何都不会编译它)我遇到了同样的错误。幸运的是,它将在C++17的MSVC16.0中得到修复,最好使用
连词
而不是折叠表达式,以避免不必要的实例化。
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;
}
template<typename Base, typename... Args>
constexpr auto all_base_of()
{
    return (std::is_base_of<Base, Args>::value && ...);
}

static_assert(all_base_of<Base, A, B, C>());