【发布时间】:2017-05-10 20:08:48
【问题描述】:
我正在使用模板并试图实现以下帮助器。
first_constructible<Types..., Args...>::type
这将返回Types 的第一种类型,它可以从Args... 构造。第一个问题显然是struct 中有两个参数包,所以我将用法改为
first_constructible<std::tuple<Types...>, Args...>::type
我通过将元组类型拆分为 first 和 rest 来实现它,使用 std::is_constructible 检查并在必要时递归。
template<typename T>
struct pop_front_tuple
{
template<typename U, typename... Us>
static std::tuple<Us...> impl(std::tuple<U, Us...>);
using type = decltype(impl(std::declval<T>())); // std::tuple with removed first type
};
template<typename Tuple, typename... Args>
struct first_constructible
{
using first_type = decltype(std::get<0>(std::declval<Tuple>()));
using type = typename std::conditional
<
std::is_constructible<first_type, Args...>::value,
first_type,
typename first_constructible<typename pop_front_tuple<Tuple>::type, Args...>::type
>::type;
};
// end of recursion
template<typename... Args>
struct first_constructible<std::tuple<>, Args...>
{
using type = void;
};
但由于某种原因它不起作用。即
first_constructible<std::tuple<std::string, int>, std::string>::type a = ""; // works, a is std::string
first_constructible<std::tuple<std::string, int>>::type a = ""; // fails, error: variable or field 'a' declared void
first_constructible<std::tuple<std::string, int>, std::string::size_type, std::string::value_type> // fails, same error
我不知道我的错误在哪里。 std::is_constructible<std::string>::value 和 std::is_constructible<std::string, std::string::size_type, std::string::value_type>::value 是真的。
【问题讨论】:
标签: c++ c++11 templates template-meta-programming