[英]How to create std::string wrapper that would keep ptr to std::string and ptr to special class function from class that created that wrapper instance?
[英]How to create a std::function alike wrapper?
尝试这样做:
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;
}
但是失败:
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))'
编译器为MSVC2013。
应该是这样的:
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
应该专门用于函数签名类型。 注意: std::function
确实更复杂。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.