简体   繁体   中英

Partial Template Specialization SFINAE

I have the following class templates:

template<bool head, bool... tail> 
struct var_and {
    static constexpr bool value = head && var_and<tail...>::value;
};

template<bool b> struct var_and<b> {
    static constexpr bool value = b;
};

template<typename... Ts>
struct type_list {};

template <typename T, typename Enable = void>
class foo;

template <typename... T>
class foo<type_list<T...>, std::enable_if_t<var_and<std::is_integral_v<T>...>::value>> {};

When I try to match the specialization:

foo<type_list<int, int, int>> test{};

I get an error:

Error C2079 'test' uses undefined class 'ECS::foo<ECS::type_list<int,int,int>,void>'

At the same time I get these errors:

more than one partial specialization matches the template argument list of class "ECS::foo<ECS::type_list<int, int, int>, void>" 
"ECS::foo<ECS::type_list<T...>, std::enable_if_t<ECS::var_and<std::is_integral_v<T>...>::value, void>>"          
"ECS::foo<ECS::type_list<T...>, std::enable_if_t<ECS::var_and<std::is_integral_v<T>...>::value, void>>"
... (The exact same error message 6 more times)

How can I use SFINAE specifically to enforce type traits of a types in a variadic type pack?

I had no trouble getting it to work for a single type argument: http://www.cppsamples.com/common-tasks/class-template-sfinae.html

I know I can simply use a static_assert, but I was wondering if it is also possible without.

Workaround could look as follows:

#include <type_traits>

template <bool...>
struct bool_pack { };

template <bool... Bs>
using var_and = std::is_same<bool_pack<true, Bs...>, bool_pack<Bs..., true>>;

template<typename... Ts>
struct type_list {};

template <typename T, typename Enable = void>
class foo;

template <typename... T>
class foo<type_list<T...>, std::enable_if_t<var_and<std::is_integral<T>::value...>::value>> {};

int main()
{
    foo<type_list<int, int, int>> {};
}

[live demo]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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