gpt4 book ai didi

c++ - 参数包感知 std::is_base_of()

转载 作者:可可西里 更新时间:2023-11-01 17:10:34 31 4
gpt4 key购买 nike

是否有可能静态断言作为模板参数提供的类型是否实现了参数包中列出的所有类型,即。参数包感知 std::is_base_of()?

template <typename Type, typename... Requirements>
class CommonBase
{
static_assert(is_base_of<Requirements..., Type>::value, "Invalid.");
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
parameter pack aware version of std::is_base_of()
public:
template <typename T> T* as()
{
static_assert(std::is_base_of<Requirements..., T>::value, "Invalid.");
return reinterpret_cast<T*>(this);
}
};

最佳答案

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 中的问号,即对于 main 中的第一行,它将扩展为 static_all_of<true, true> , 对于第二行,它将是 static_all_of<true, false, true>

关于c++ - 参数包感知 std::is_base_of(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13562823/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com