【发布时间】:2020-01-09 01:59:27
【问题描述】:
我有一组类,如 A、B、C 和一个包含这些类的元组,如下所示:
struct A {
std::string name{"a"};
};
struct B {
std::string name{"b"};
};
struct C {
std::string name{"c"};
};
// only first items A(), B(), C() do matter, other are arbitrary
auto t = std::make_tuple(
std::make_tuple(A(), 1, 2, 3),
std::make_tuple(B(), 4, 5, 6),
std::make_tuple(C(), 7, 8)
);
我的目标逻辑是通过匹配第一个元素的类型从容器元组中选择一个元组。所以,通过上面的例子,我想得到字符串'b',当调用这样的东西时:
std::string the_b = having_first_of_type<B, decltype(t)>::get().name;
我正在尝试使用模板获得解决方案:
// a template for getting first item from N-th tuple int Tuples
template <std::size_t N, typename... Tuples>
using first_of_nth = std::tuple_element<0, std::tuple_element<N, std::tuple<Tuples...>>>;
template <std::size_t N, class T, class... Tuples>
struct having_first_of_type;
template <std::size_t N, class T, class... Tuples>
struct having_first_of_type<N,
typename std::enable_if<std::is_same<T, typename first_of_nth<N, Tuples...>::type>::value, T>::type* = nullptr>
{
static auto& get(const std::tuple<Tuples...>& tuple) {
return std::get<N>(tuple);
}
};
template <std::size_t N, class T, class... Tuples>
struct having_first_of_type<N,
typename std::enable_if<!std::is_same<T, typename first_of_nth<N, Tuples...>::type>::value, T>::type* = nullptr> : having_first_of_type<N-1, T, Tuples...>;
template <std::size_t N, class T, class... Tuples>
struct having_first_of_type<0, T, Tuples...> {}
而且我无法以正确的方式形成专业。对于第一个(std::is_same 为真)编译器说:error: expected '>' for position of '= nullptr'。看起来它不接受 T* 的默认值,但我很困惑为什么..
什么是错误?或者,也许有更好的方法来获得我想要的东西?
更新 以下是 2 个可行的解决方案:来自 N. Shead 和 @n314159 - 谢谢!
我忘了提到我尝试使用 C++14 来获取它,但解决方案是针对 C++17 的。
C++17 也可以。
【问题讨论】:
-
item()应该是内部tuple对象,或者它的第一个元素,类型为B?你说“从容器元组中选择一个元组”,然后有 ...item().name虽然std::tuple没有name成员。 -
是的,@aschepler,你是对的,当然
item()是错的——应该有get()