如何在c++中使用模板参数调用函子?

问题描述 投票:0回答:1

我想在

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

c++ templates metaprogramming
1个回答
0
投票

在您的示例中, 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{} );
}
© www.soinside.com 2019 - 2024. All rights reserved.