c++ - Applying a variadic function with std::apply -
is possible apply variadic function tuple std::apply?
for example, following code works fine gcc 6.2.1:
void print_t(std::string i, std::string j) { std::cout << << " " << j << std::endl; } int main() { std::tuple<std::string, std::string> t{"ab", "cd"}; std::experimental::apply(print_t, t); return 0; }
but if try apply variadic function:
template<typename t> void vprint(t && t) { std::cout << std::forward<t>(t) << std::endl; } template<typename t, typename ... ts> void vprint(t && t, ts ... ts) { std::cout << std::forward<t>(t) << " "; vprint<ts...>(std::forward<ts>(ts)...); } int main() { std::tuple<std::string, std::string> t{"fd", "ab"}; std::experimental::apply(vprint, t); return 0; }
the compiler complains cannot deduce template arguments of vprint
. ok, let's write them explicitly:
std::experimental::apply(vprint<std::string, std::string>, t);
now compiler ends obscure errors expose standard library internals.
i wrote own implementation of std::apply
in c++11 , understand why can't deduce arguments of variadic function template. but, in theory, std::apply
has information needed deduction.
so application of variadic functions not yet implemented feature in gcc6? c++17-compatible compilers allow such application? if not, allow application of instantiated variadic template functions, vprint<std::string, std::string>
?
with vprint<std::string, std::string>
, must pass r-value references, so
std::experimental::apply(vprint<std::string, std::string>, std::move(t));
the better way use functor (thanks generic lambda):
std::experimental::apply([](auto&&... args) { vprint(std::forward<decltype(args)>(args)...); }, t);
Comments
Post a Comment