【发布时间】:2019-01-25 23:49:41
【问题描述】:
我正在开发模板MyTemplate,它将以下列方式使用:
using Alias = MyTemplate<std::pair<int, char>,
std::pair<int, double>,
std::pair<int, unsigned int>>;
现在我们可以假设MyTemplate 将只获取对类型的列表。此外,所有对类型都应具有相同的第一种类型,而第二种类型必须有所不同。
我想在MyTemplate 中“捕捉”这对first_type。我想出了以下定义:
template<typename... Ts>
struct MyTemplate
{
using first_type = std::decay_t<decltype((Ts::first_type, ...))>;
// ...
};
当我在不同模板的上下文中使用typename MyTemplate::first_type 时,一切正常。我只收到一个警告:
warning: left operand of comma operator has no effect [-Wunused-value]
using first_type = std::decay_t<decltype((Ts::first_type, ...))>;
^
但是,我无法创建 Alias 的实例,因为我收到了该错误:
error: missing 'typename' prior to dependent type name 'std::pair<int, char>::first_type'
您对“通用”解决方案有任何想法吗?我可以使用 C+17。
【问题讨论】:
-
std::decay_t<decltype((Ts::first_type, ...))>没有意义。您使用,折叠表达式,但使用类型作为操作数? -
不清楚你真正想要的行为是什么。
first_type应该是什么?你有很多对 - 你试图实现的实际功能是什么 -
问题出在“创建实例”部分,而不是上面显示的模板的定义(尽管这也有其自身的问题)。而且由于“创建实例”部分没有显示,所以这个问题无法回答,但很可能是a duplicate of this one,或者of this one。
-
另外,您是否有不想使用
MyTemplate<int, char, double, unsigned int>而不是MyTemplate<std::pair<int, char>, std::pair<int, double>, std::pair<int, unsigned int>>的原因?您将能够轻松地在模板中生成pair类型的列表,并且您不需要提取第一个类型。
标签: c++ templates c++17 variadic-templates template-argument-deduction