从参数包问题构造boost :: variant

时间:2014-01-02 20:19:32

标签: c++ boost typetraits boost-variant

我尝试编写允许我从参数包中构造boost::variant<>的函数。换句话说,我正在尝试构造boost::variant<>::types类型之一,其构造函数的签名与包匹配,然后转换为boost::variant<>。我天真地写了以下内容:

#!/usr/bin/env sh -vex
WARN="-W -Wall -Wextra"
INCLUDE="-isystem /c/libs/boost-trunk"
OPT="-Ofast"
g++ -x c++ - -std=gnu++1y $INCLUDE $WARN $OPT -o a <<__EOF && ./a && echo -e "\e[1;32msucceeded\e[0m" || echo -e "\e[1;31mfailed\e[0m"
#include <boost/assert.hpp>
#include <boost/variant.hpp>
#include <boost/mpl/placeholders.hpp>
#include <boost/mpl/find_if.hpp>
#include <boost/mpl/deref.hpp>
#include <boost/type_traits.hpp>

#include <type_traits>

#include <cstdlib>

struct A
{
    A() = default;
};

static_assert( std::is_constructible< A >::value,           " A()"        );
static_assert(!std::is_constructible< A, int >::value,      "!A(int)"     );
static_assert(!std::is_constructible< A, int, int >::value, "!A(int, int)");

struct B
{
    B(int) {}
};

static_assert(!std::is_constructible< B >::value,           "!B()"        );
static_assert( std::is_constructible< B, int >::value,      " B(int)"     );
static_assert(!std::is_constructible< B, int, int >::value, "!B(int, int)");

struct C
{
    C(int, int) {}
};

static_assert(!std::is_constructible< C >::value,           "!C()"        );
static_assert(!std::is_constructible< C, int >::value,      "!C(int)"     );
static_assert( std::is_constructible< C, int, int >::value, " C(int, int)");

using V = boost::variant< A, B, C >;

template< typename V,
          typename ...O >
inline constexpr
V construct(O &&... _o)
{
    using types = typename V::types;
    using predicate = std::is_constructible< boost::mpl::_1, O... >; // I think, that the problem is exactly here.
    using iter = typename boost::mpl::find_if< types, predicate >::type;
    using deduced_type = typename boost::mpl::deref< iter >::type;
#if 1
    return deduced_type(std::forward< O >(_o)...);
#else
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wmissing-field-initializers"
    return deduced_type{std::forward< O >(_o)...}; // second part of the question
#pragma GCC diagnostic pop
#endif

}

int main()
{
    V a = construct< V >();
    BOOST_ASSERT(a.type() == typeid(A));
    V b = construct< V >(0);
    BOOST_ASSERT(b.type() == typeid(B));
    V c = construct< V >(0, 0);
    BOOST_ASSERT(c.type() == typeid(C));
    return EXIT_SUCCESS;
}
__EOF

它产生了一组可爱的错误消息,据我所知,其基本含义是std::is_constructibleboost::mpl::库不兼容(或者更确切地说不是与 boost::mpl::)中的占位符兼容。反过来,boost::库本身不包含(假设兼容的)boost::is_constructible类型特征。

另一个相关的问题是处理像struct A {}; struct B {int _1;}; struct C {int _1; int _2;};这样的类,并通过花括号而不是括号来构造它们。最后提到的问题的主要方面是缺少类型特征,它推断是否可以从某些参数包构造某些类型。 solution不适用于boost::mpl::

0 个答案:

没有答案