我想在
c++17
中做这样的事情:
template<class FuncT>
void call_function(FuncT&& f)
{
f<int>(); // issue
}
template<typename U>
void foo()
{
U u = 42;
// ...
}
int main()
{
call_function(foo);
return 0;
}
但是
g++
给出 error: expected primary-expression before ‘int’
。
在
int
中调用函子f
时如何指定类型call_function
?
在您的示例中, foo 是一个函数。函数不是对象,因此不能在内部进行专门化
call_function()
。
函子是对象,并且可以专门化。
#include <iostream>
#include <type_traits>
template<typename FuncT>
void call_function( FuncT&& fctor ) {
// ugly, but we can retrieve the function operator as template<int>
std::forward<FuncT>(fctor).template operator()<int>();
}
struct Functor {
template<typename T>
void operator()() {
std::cout << "functor called for type T=" << typeid(T).name();
}
};
int main() {
call_function( Functor{} );
}