Attempted this:
template <class R, class... Ts>
class MyFunction
{
public:
using func_type = R(*)(Ts...);
MyFunction(func_type f)
: m_func(f)
{
}
R operator()(Ts ... args)
{
return m_func(args...);
}
private:
func_type m_func;
};
int Testfn(int a)
{
std::cout << "value is " << a;
return 42;
}
void Testing()
{
MyFunction<int(int)> func(Testfn);
std::cout << "Ret is " << func(1) << std::endl;
}
But fails with:
error C2064: term does not evaluate to a function taking 1
C2091: function returns function
C2091: function returns
C2664: 'MyFunction<int (int),>::MyFunction(const MyFunction<int
(int),> &)' : cannot convert argument 1 from 'int (__cdecl *)(int)' to
'int (__cdecl *(__cdecl
*)(void))'
Compiler is MSVC2013.
It should be like this:
template <typename T>
class MyFunction;
template<typename R, class... Ts>
class MyFunction<R(Ts...)>
{
public:
using func_type = R(*)(Ts...);
MyFunction(func_type f)
: m_func(f)
{
}
R operator()(Ts ... args)
{
return m_func(args...);
}
private:
func_type m_func;
};
MyFunction
should be specialized for function signature type. Note: std::function
is really more complicated.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.