可变参数模板函数解包顺序
Variadic template function unpack order
我有这个代码:
template<typename ...T>
struct Test
{
void call(string str)
{
abc(get<T>(str)...);
}
template<typename U>
string get(string& inp)
{
string ret{ inp[0] };
inp.erase(0, 1);
cout << ret << endl; // first "a", next "b", next "c" - everything is ok
return ret;
}
void abc(string a, string b, string c)
{
cout << a << " " << b << " " << c << endl; // "b c a" - why?
}
};
我是这样称呼它的:
Test<int, bool, float> test;
test.call("abc");
输出是我期望b c a
a b c
.此外get()
函数中,我有一个正确的顺序。这是为什么呢?我找不到有关此订单的任何规则。
未指定函数参数的计算顺序。
abc(get<T>(str)...);
这本质上与:
abc(get<T1>(str), get<T2>(str), get<TN>(str));
您可以通过生成一个数组来存储字符串,然后从该数组调度来强制执行计算顺序:
template <std::size_t N, std::size_t... Idx>
void call_helper(std::array<std::string, N> arr, std::index_sequence<Idx...>) {
abc(std::get<Idx>(arr)...);
}
void call(string str)
{
std::array<std::string,sizeof...(T)> arr { get<T>(str)... };
call_helper(arr, std::index_sequence_for<T...>{});
}
不保证函数调用参数的顺序。因此,abc(get<T>(str)...);
没有定义的顺序。
有关更多详细信息,请参阅C++函数参数中的计算顺序。
相关文章:
- CMake-按正确顺序将项目与C运行时对象文件链接
- 函数调用中参数的顺序重要吗
- 为什么不;名字在地图上是按顺序排列的吗
- 将Integer转换为4字节的unsined字符矢量(按大端字节顺序)
- 数到第n个楼梯的路(顺序无关紧要)
- 优先顺序:智能指针和类析构函数
- 在循环中按顺序遍历成员变量
- 独立读取-修改-写入顺序
- QML按钮点击功能执行顺序
- C++中数据类型修饰符的顺序
- 当比特(而不是字节)的顺序至关重要时的持久性
- 如何检查参数包是否具有执行顺序中的确切类型
- 参数包扩展顺序
- C++11:变分模板函数参数包扩展执行顺序
- 以错误的顺序将函数应用于参数包中的每个元素
- 可变参数模板函数解包顺序
- 原始数据包创建导致 IP 字段顺序不正确
- 什么可能导致数据包的字节顺序部分混乱?
- 构造函数执行顺序/顺序:函数中静态变量(类实例)的依赖初始化
- Boost::asio包的顺序和连续性