提问者:小点点

C++11中的连词类型特征


我需要检查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::conferency

用C++11实现关联的简单方法是什么? 我想带有递归的SFINAE就足够了,但是我不能完全理解它。


共2个答案

匿名用户

您需要一个工具,它将对变量参数执行连接操作。

#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://godbolt.org/z/d3jvm4

基于https://en.cppreference.com/w/cpp/types/concounty,它在C++17中可用。

匿名用户

试图从另一个角度看问题。。。

如果我没有说错,std::tuple是默认可构造的当(当且仅当)每种类型的元组都是默认可构造的,那么

 template <typename
    = typename std::enable_if<std::is_default_constructible<std::tuple<A, B...>::value>::type>
 Foo()
  { }

或者还

 template <typename = decltype(std::tuple<A, B...>())>
 Foo()
  { }

相关问题


MySQL Query : SELECT * FROM v9_ask_question WHERE 1=1 AND question regexp '(c++11|中|连词|类型|特征)' ORDER BY qid DESC LIMIT 20
MySQL Error : Got error 'repetition-operator operand invalid' from regexp
MySQL Errno : 1139
Message : Got error 'repetition-operator operand invalid' from regexp
Need Help?