c++ - Find out how this variadic templated function works -
in this answer have seen c++11 code, don't understand (but to).
there, variadic template function defined, (maybe?) takes arguments passed , inserts them std::ostringstream
.
this function (see complete working example @ linked answer):
template<typename t, typename... ts> std::string createstring(t const& t, ts const&... ts) { using expand = char[]; std::ostringstream oss; oss << std::boolalpha << t; (void)expand{'\0', (oss << ts, '\0')...}; return oss.str(); }
when had guess, i'd say, character array created , initialized \0
-bytes, , insertion of function's arguments stream happens side effect of initialization (part of comma expression). in end, array contains many nulls items inserted stream. it's casted void in order avoid compiler warning (unused variable). similar this:
char arr[] = {'\0', (oss << t1, '\0'), (oss << t2, '\0'), ..., (oss << tn, '\0')};
is attempt describe function's workings accurate? can explain design decision might relevant here, , why beneficial implement way (the alternative compile-time recursion, guess)?
after receiving helpful hints in question's comment section figure out of points:
- the feature being used called pack expansion. works described in op: temporary array initialized side effect of stream insertion. detailed description of feature can found here:
- this work-around necessary avoid recursion approach, less efficient. in c++17 work-around no longer needed, because of introduced fold expressions:
- http://en.cppreference.com/w/cpp/language/fold
- see question's answers: variadic template pack expansion
- the first array element initialized
\0
avoid program being ill-formed if function called 1 argument. else, array object created empty, incomplete type (array of unknown bounds), illegal. further reading:
Comments
Post a Comment