'How to create a simple version of std::function class
Suppose that I want to create a simple version ofstd::function, which has following behaviors:
1. function(){} -> A void constructor
2. function(_ReturnType, Args... vlist) -> To convert function pointer to a funcion object
3. _ReturnType operator() (_ArgTypes... vlist) -> To call function by fn(Args...)
I have already tried to write down a version, but it seems to fail during compiling... I design it like this:
template <typename ReType, typename... _ArgTypes>
class function
{
protected:
ReType(*fn) = NULL;
public:
function() {}
function(ReType R, _ArgTypes... vlist) { fn = R; }
ReType operator()(_ArgTypes... vlist)
{
return fn(vlist...);
}
};
With compiler error:
In file included from main.cpp:11:
functional.h: In instantiation of 'class nuts::function<double(double)>':
main.cpp:102:27: required from here
functional.h:16:16: error: function returning a function
ReType operator()(_ArgTypes... vlist)
^~~~~~~~
main.cpp: In function 'int main()':
main.cpp:103:19: error: no match for call to '(nuts::function<double(double)>) (double)'
std::cout << fn(2.0) << std::endl;
^
Solution 1:[1]
Based on the solution given by @mch
template <typename FuncType>
class function
{
FuncType *(fn) = NULL;
public:
function(FuncType R) : fn{R} {}
template <typename... _ArgTypes>
auto operator()(_ArgTypes... vlist)
{
return fn(vlist...);
}
};
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | BioElecthetic |