繁体   English   中英

知道参数包的std :: is_base_of()

[英]Parameter pack aware std::is_base_of()

是否有可能静态断言作为模板参数提供的类型是否实现了参数包中列出的所有类型,即。 参数包知道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的fold表达式,这变得微不足道:

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 ++ 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>());

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM