Function templates represent an infinite overload set, so unless you have a target type that is compatible with a specialization, deduction of the function type always fails. For example:
template<class T> void f(T);
template<class T> void h(T);
void g() {
h(f); // error: couldn't infer template argument 'T'
h(f<int>); // OK, type is void (*)(int)
h<void(int)>(f); // OK, compatible specialization
}
From above we can see that the validity of the program demands that we specify the template arguments for the function template, when in general it isn't always intuitive to specify them. You can instead make print
a functor with a generic overloaded call operator as an extra level of indirection:
struct print {
template<typename T>
void operator()(T&& x) const {
std::cout << x;
}
};
Now you can have execute
accept any Callable and invoke it with the input:
template<class T, class Op>
void execute(T&& input, Op&& op) {
std::forward<Op>(op)(std::forward<T>(input));
}
void g() { execute(1, print{}); }
Generic lambdas (C++14) make this a lot more concise:
execute(1, [] (auto&& x) { std::cout << x; });
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…