【发布时间】:2021-11-29 06:24:15
【问题描述】:
问题陈述
我正在尝试传递一个包含此类通用属性的结构
template <typename Value>
struct ColumnValue {
std::string columnName;
Value value;
};
我还想创建一个接受未知数量参数的函数
print(T... args)
这些 args 将是具有 1 个或多个的 ColumnValue 对象类型...
我希望打印函数根据“值”的类型来做不同的事情。
期望的结果
222
"hellooooo"
代码
#include <iostream>
template <typename Value>
struct ColumnValue {
std::string columnName;
Value value;
};
template <template<typename> typename ...X, typename ...Y>
void print(std::string firstArg, const X<Y>& ...args) {
for(auto val : {args...}) {
std::cout << val.value << std::endl;
}
}
int main() {
ColumnValue<int> v{
.columnName="hello",
.value=222
};
ColumnValue<std::string> d{
.columnName="hello",
.value="hellooooo"
};
print("", v, d);
return 0;
}
错误信息
: 在'void print(std::string, const X& ...) [with X = {ColumnValue, ColumnValue}; Y = {int, std::__cxx11::basic_string, 标准::分配器 >};标准::字符串 = std::__cxx11::basic_string]’: :28:19: 需要来自 这里:12:5:错误:无法推断 来自‘{args#0, args#1}’的‘std::initializer_list&&’ 12 | for(自动验证:{args...}){ | ^~~ :12:5: 注意:推断参数“auto”的冲突类型(“ColumnValue”和 ‘列值>’)
【问题讨论】:
-
std::initializer_list只能包含单一类型的元素。您可以使用折叠表达式:(std::cout << ... << args.value) << std::endl;. -
我在加法
auto只能是单一类型
标签: c++ templates variadic-templates