#include <functional> int func(int x, int y) { return x+y; } int main() { typedef std::function<int(int, int)> Funcp; Funcp funcp = func; return 0; }
But is it possible to point to a template function?
#include <functional> template<class T> T func(T x, T y) { return x+y; } int main() { typedef std::function<?(?, ?)> Funcp; Funcp funcp = func; return 0; }
Defining a Function TemplateA function template starts with the keyword template followed by template parameter(s) inside <> which is followed by the function definition. In the above code, T is a template argument that accepts different data types ( int , float , etc.), and typename is a keyword.
To instantiate a template function explicitly, follow the template keyword by a declaration (not definition) for the function, with the function identifier followed by the template arguments. template float twice<float>(float original); Template arguments may be omitted when the compiler can infer them.
Explanation: As a template feature allows you to write generic programs. therefore a template function works with any type of data whereas normal function works with the specific types mentioned while writing a program. Both normal and template function accepts any number of parameters. 4.
Class template std::function is a general-purpose polymorphic function wrapper. Instances of std::function can store, copy, and invoke any Callable target -- functions, lambda expressions, bind expressions, or other function objects, as well as pointers to member functions and pointers to data members.
There is no such thing as a template function in C++ — what people casually mention as "template functions" are actually function templates : templates which define functions.
As such, func
in your second example above is not a function, it's a (function) template, and it cannot be used in the same way as a function can. In particular, std::function
expects to be provided with a function.
How you can work around this depends on what you are trying to achieve. If you're trying to make the code that uses the function work with any type, you can simply place that code in a function or class template:
template <typename T> void use_function(T t) { typedef std::function<T(T,T)> Funcp = func<T>; // use Funcp here }
What you will not be able to do, however, is use late binding with universal type quantifiers ("can be applied to any type"), because "can be applied to any type" is necessarily resolved at compile-time in C++. That's just how it rolls.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With