带有模板和 boost 的函数
我尝试编写一个函子来使用绑定和一些模板调用 boost 函数。所以我有这个 main :
int function(char c)
{
std::cout << c << std::endl;
return (0);
}
int main()
{
Function<int (char)> fb = boost::bind(&function, _1);
fb('c');
return (0);
}
这是我的类 Function
:
template<typename F>
class Function
{
private:
F functor;
public:
Function()
{
this->functor = NULL;
};
Function(F func)
{
this->functor = func;
};
template <typename P>
void operator()(P arg)
{
(*this->functor)(arg);
};
void operator=(F func)
{
this->functor = func;
};
};
我有一个问题:当我尝试编译时,我遇到了这些错误:
error C2440: 'initializing' : cannot convert from 'boost::_bi::bind_t<R,F,L>' to 'Function<F>'
IntelliSense: no suitable user-defined conversion from "boost::_bi::bind_t<int, int (*)(char), boost::_bi::list1<boost::arg<1>>>" to "Function<int (char)>" exists
有人可以帮助我吗?
I try to write a functor to call a boost function with bind and some template. So i have this main :
int function(char c)
{
std::cout << c << std::endl;
return (0);
}
int main()
{
Function<int (char)> fb = boost::bind(&function, _1);
fb('c');
return (0);
}
and this is my class Function
:
template<typename F>
class Function
{
private:
F functor;
public:
Function()
{
this->functor = NULL;
};
Function(F func)
{
this->functor = func;
};
template <typename P>
void operator()(P arg)
{
(*this->functor)(arg);
};
void operator=(F func)
{
this->functor = func;
};
};
i have a problem : when i try to compile i have these errors :
error C2440: 'initializing' : cannot convert from 'boost::_bi::bind_t<R,F,L>' to 'Function<F>'
IntelliSense: no suitable user-defined conversion from "boost::_bi::bind_t<int, int (*)(char), boost::_bi::list1<boost::arg<1>>>" to "Function<int (char)>" exists
Someone can help me ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
boost::bind
将返回未指定的内容,但可转换为boost::function
。你没有理由拥有自己的函数
类。看这个简单的例子:
未指定
返回类型对您的情况意味着什么?您需要删除Function
的类型并需要编写一个名为
AnyFunction
的东西。为什么?因为您永远无法在 C++03(甚至 C++11,例如仅接受特定类型作为函数参数)中拼出Function
的模板参数类型。boost::bind
will return something unspecified, but convertible to aboost::function
. There is no reason for you to have your ownfunction
class.Look at this simple example:
What does that
unspecified
return type mean for your case? You need to erase the type ofFunction
andneed to write something called
AnyFunction
. Why? Because you will never be able to spell out the type of the template argument ofFunction
in C++03 (and even C++11, for e.g. accepting only a specific type as a function argument).