问题
I'm writing some template functions in C++, but I'm not sure if it's possible to define a template function that infers the types of its parameters.
I tried to define a template with inferred parameter types, but this example won't compile:
template <auto>
auto print_stuff(auto x, auto y)
{
std::cout << x << std::endl;
std::cout << y << std::endl;
}
It works when I give a unique name to each parameter type, but this seems somewhat redundant:
#include <iostream>
#include <string>
template <class Redundant_1,class Redundant_2>
auto print_stuff(Redundant_1 x, Redundant_2 y)
{
std::cout << x << std::endl;
std::cout << y << std::endl;
}
int main()
{
print_stuff(3,"Hello!");
return 0;
}
Is it possible to define a template with inferred parameter types instead of giving each type a unique name?
回答1:
You can dispense with the template-header and names for the parameter-types if your compiler supports concepts, which isn't generally enabled even if asking for experimental C++2a mode.
On gcc for example, it must be separately enabled with -fconcepts
.
See live on coliru.
#include <iostream>
#include <string>
auto print_stuff(auto x, auto y)
{
std::cout << x << std::endl;
std::cout << y << std::endl;
}
int main()
{
print_stuff(3,"Hello!");
return 0;
}
As an aside, avoid std::endl
and use std::flush
in the rare cases you cannot avoid costly manual flushing. Also, return 0;
is implicit for main()
.
来源:https://stackoverflow.com/questions/56758349/can-the-types-of-parameters-in-template-functions-be-inferred