Function pointer as a template

2020-06-23 06:42发布

How to write a function pointer as template?

template <typename T>
T (*PtrToFunction)(T a); 

标签: c++
4条回答
倾城 Initia
2楼-- · 2020-06-23 06:46

If you mean create a type for that function, you could do something like this:

template<typename T>
struct Function {
    typedef T (*Ptr)(T);
};

Then use it like

int blah(Function<int>::Ptr a) { }
查看更多
趁早两清
3楼-- · 2020-06-23 07:07

It's ok on Visual Studio 2015 and on GCC you should use command line option -std=c++11

template<class T> using fpMember = void (T::*)(); 
查看更多
爷的心禁止访问
4楼-- · 2020-06-23 07:08

I am assuming you are trying to declare a type (you cannot declare a "template variable" without a concrete type).

C++03 doesn't have template typedefs, you need to use a struct as a workaround:

template <typename T>
struct FuncPtr {
    typedef T (*Type)(T a);
};

...

// Use template directly
FuncPtr<int>::Type intf;

// Hide behind a typedef
typedef FuncPtr<double>::Type DoubleFn;
DoubleFn doublef;

C++11 template aliases will eliminate the struct workaround, but presently no compilers except Clang actually implement this.

template <typename T>
typedef T (*FuncPtr)(T a);

// Use template directly
FuncPtr<int> intf;

// Hide behind a typedef
typedef FuncPtr<double> DoubleFn;
DoubleFn doublef;
查看更多
混吃等死
5楼-- · 2020-06-23 07:10

You can not do that. You can only create function pointers with concrete type.

查看更多
登录 后发表回答