c++ SFINAE:使用模板结构的模板子级

polhcujo  于 2023-03-20  发布在  其他
关注(0)|答案(1)|浏览(122)

做这种事的正确方法是什么?
我想在参数包上使用如下条件:

static_assert(all_of<ChildTypes ...>::are_in<ParentTypes ...>::value);

简而言之,我有这样的代码:

template <class ... Types> struct is_in
{
    template <class Arg>
    struct test : any_of<Types ...>::is_same_as<Arg> {}; // error C2059
};

template <class ... Args>
struct all_of
{
    template <class ... Types>
    struct are_in : all_fulfill<typename is_in<Types ...>::test, Args ...> {};

    template <class Type>
    struct are : all_fulfill<typename is_same_as<Type>::test, Args ...> {};
};

其中any_of<Types...>::is_same_as<Type>::valueall_of<Types...>::are<Type>::value在函数中使用时效果很好,因此all_fulfill和'any_fulfills'也效果很好(总是true_type或false_type)。
当尝试调用are_in时,我遇到以下错误:

error C2059: syntax error: '<'
error C2039: 'value': is not a member of 'is_in<bool,int>::test<Head>' with [ Head=int ]
error C2065: 'value': undeclared identifier
error C2975: '_Test': invalid template argument for 'std::conditional', expected compile-time constant expression

作为背景:

template < template <class> typename Test, typename... List >
struct all_fulfill : std::false_type {};

template < template <class> typename Test, typename Head, typename... List >
struct all_fulfill<Test, Head, List ...>
    : std::conditional< Test<Head>::value, // error C2065 // error C2975
    all_fulfill<Test, List...>, // error C2039
    std::false_type
    >::type {};

template < template <class> typename Test >
struct all_fulfill<Test> : std::true_type {};

尝试:
struct is_in中,为父类型添加别名,例如:using AnyOfTypes = any_of<Types ...>;struct AnyOfTypes : any_of<Types ...> {}
预期结果:
all_of<ChildTypes ...>::are_in<ParentTypes ...>::value应返回正确的bool。

6g8kf2rb

6g8kf2rb1#

这个怎么样?

#include <type_traits>

template <typename... Types>
struct all_of
{
    template <typename Arg>
    constexpr static bool contains = (std::is_same_v<Arg, Types> || ...);

    template <typename... Args>
    constexpr static bool are_in = (all_of<Args...>::template contains<Types> && ...);
};

int main()
{
    static_assert(all_of<bool, int>::are_in<int, double, bool>);
    return 0;
}

https://godbolt.org/z/Y1j7dedsh

相关问题