I have this code:
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?
}
};
I'm calling it like this:
Test<int, bool, float> test;
test.call("abc");
And the output is b c a
thought I expect a b c
. Moreover in get()
function I have a correct order. Why is this? I can't find any rule about this order.
The order of evaluation of function arguments is unspecified.
abc(get<T>(str)...);
That is essentially the same as:
abc(get<T1>(str), get<T2>(str), get<TN>(str));
You could enforce evaluation order by generating an array to store the strings, then dispatching from that array:
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...>{});
}
The order of function call arguments are not guaranteed. Therefore, abc(get<T>(str)...);
doesn't have a defined order.
See Order of evaluation in C++ function parameters for more details.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With