How to use the generic functions pointer as a template parameter?

Can I use the generic function pointer as a template parameter? The function pointer template can take free functions, member functions, and lambda functions. For simplicity, assuming functions have only one argument, e.g.

template<class ArgumentT, class ReturnT, function* f> struct A { // f is used somewhere. }; 
+6
source share
4 answers

A regular template argument may refer to a function.

 #include <iostream> template <class ArgT, class RetT, class F> struct A { F f; public: A(F f) : f(f) {} RetT operator()(ArgT arg) { return f(arg); } }; int unchanged(int i) { return i; } int main(){ A < int, int, int(*)(int)> t{ unchanged }; for (int i = 0; i < 10; i++) std::cout << t(i) << "\n"; } 

There is nothing to limit the argument of the function template - you can just as easily use some class that overloads operator() and call it instead (and, in fact, this is often preferable).

+8
source

I would recommend using std :: function <> if you can use C ++ 11 or boost :: function <> if you cannot:

 template<class ArgumentT, class ReturnT > struct A { typedef std::function< ReturnT( ArgumentT ) > Function; void foobar( Function f ) { ReturnT ret = f( arg ); } }; 

In this case, you can pass a function pointer, functor, lambda, or use std :: bind or boost :: bind with almost any function whose signature does not match. I'm not sure if you need a template in this case, you can use std :: function directly, but it depends on your code.

+2
source

You combine types and data, you need something more:

 template<class ArgumentT, class ReturnT, typename F*> struct A { //use F* to refer to f somewhere }; 
0
source

You can achieve something close:

 template<class ArgumentT, class ReturnT, class F, F f> struct A; template<class ArgumentT, class ReturnT, ReturnT (*f)()> struct A<ArgumentT, ReturnT, ReturnT (*)(), f> { // f is used somewhere. }; template<class ArgumentT, class ReturnT, class C, ReturnT (C::*f)()> struct A<ArgumentT, ReturnT, ReturnT (C::*)(), f> { // f is used somewhere. }; 

... but you cannot take something like std::function<ReturnT ()> as a template parameter of a non-pig type. Specialization for function pointers will also accept unassembled lambdas.

0
source

Source: https://habr.com/ru/post/954610/


All Articles