我需要检查可变参数std::enable_if
:
使用C ++ 17我会写:
template <typename A, typename ...B>
class Foo : public A, public B...
{
public:
template <typename = std::enable_if_t<std::is_default_constructible_v<A> &&
(std::is_default_constructible_v<B> && ...)>>
Foo()
{}
Foo(A &&a, B && ... b)
: A(std::forward<A>(a)),
B(std::forward<B>(b))...
{}
};
但是C ++ 11没有以这种方式扩展参数包的功能。它也没有提供std::conjunction
。
与C ++ 11结合实现的简单方法是什么?我想带有递归的SFINAE就足够了,但是我无法缠住它。
您需要一个工具来对可变参数进行合取运算。
#include <iostream>
#include <type_traits>
template<class...> struct conjunction : std::true_type { };
template<class B1> struct conjunction<B1> : B1 { };
template<class B1, class... Bn>
struct conjunction<B1, Bn...>
: std::conditional<bool(B1::value), conjunction<Bn...>, B1>::type {};
template <typename A, typename ...B>
class Foo : public A, public B...
{
public:
template <typename std::enable_if<std::is_default_constructible<A>::value &&
conjunction<std::is_default_constructible<B>...>::value, bool>::type = true>
Foo()
{}
Foo(A &&a, B && ... b)
: A(std::forward<A>(a)),
B(std::forward<B>(b))...
{}
};
struct A {};
struct B {};
struct C {
C(int x) {}
};
int main()
{
Foo<A, B> foo;
//Foo<A, B, C> bar;
return 0;
}
基于https://en.cppreference.com/w/cpp/types/conjunction(可在C ++ 17中使用)。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句