nik*_*ack 3 c++ variadic-templates c++11
我有这个代码:
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?
}
};
Run Code Online (Sandbox Code Playgroud)
我这样称呼它:
Test<int, bool, float> test;
test.call("abc");
Run Code Online (Sandbox Code Playgroud)
输出被b c a认为是我期待的a b c.此外,在get()功能我有一个正确的顺序.为什么是这样?我找不到关于这个订单的任何规则.
函数参数的评估顺序未指定.
abc(get<T>(str)...);
Run Code Online (Sandbox Code Playgroud)
这基本上与:
abc(get<T1>(str), get<T2>(str), get<TN>(str));
Run Code Online (Sandbox Code Playgroud)
您可以通过生成用于存储字符串的数组,然后从该数组调度来强制执行评估顺序:
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...>{});
}
Run Code Online (Sandbox Code Playgroud)