我正在尝试编写一个模板函数,该函数根据对象和类方法返回可调用对象。这个想法是:
class Obj : public boost::enable_shared_from_this<Obj>
{
public:
bool Meth1(int a) { return a == 7; }
int Meth2(double a) { return a * 2; }
};
template<class Tobj, typename Tmeth>
auto Creator(boost::shared_ptr<TObj> shobj, Tmeth meth) -> decltype("callable based on Tmeth")
{
return boost::bind(&meth, shobj, _1);
}
用法如下:
boost::shared_ptr<Obj> obj = boost::make_shared<Obj>();
// mm would be of type boost::function<bool(int)>
auto mm = Creator(obj->shared_from_this(), Obj::Meth1);
bool isSeven = mm(7);
我找不到这样做的方法。作为一个有趣的事实,在进行实验时,我绝望的尝试之一就是:
template<class Tobj, typename Tmeth>
auto return_mm(Tobj &obj, Tmeth meth)
-> decltype(boost::bind(&meth, obj.shared_from_this(), _1))
{
return boost::bind(&meth, obj.shared_from_this(), _1);
}
我知道,看起来很傻,这让VC ++ 10崩溃了。任何的想法?也许我应该使用boost :: phoenix?
更新
这可以在VC ++ 10上编译和工作,但是,严肃地说,看起来很糟糕:
template<typename TOBJ, typename TMETH>
auto Create(boost::shared_ptr<TOBJ> sobj, TMETH mm) -> decltype( boost::bind(mm, sobj, _1) )
{
return boost::bind(mm, sobj, _1);
}
部分&#34; - &GT; decltype(boost :: bind(mm,sobj,_1))&#34;对我来说不好看。此外,如果您尝试使用期望两个参数的方法,它会破坏编译器!
答案 0 :(得分:0)
修正了代码中的一些错误
已更新。已添加boost::function
示例。
class Obj : public boost::enable_shared_from_this<Obj>
{
public:
bool Meth1(int a) { return a == 7; }
int Meth2(double a) { return a * 2; }
};
template<class Tobj, typename Tmeth>
auto Creator(boost::shared_ptr<Tobj> shobj, Tmeth meth)
{
return boost::bind(meth, shobj, _1);
}
template<typename Targ, class Tobj, typename Tmeth>
boost::function<bool (Targ)> Creator2(boost::shared_ptr<Tobj> shobj, Tmeth meth)
{
return boost::bind(meth, shobj, _1);
}
int main() {
boost::shared_ptr<Obj> obj = boost::make_shared<Obj>();
// mm would be of type boost::function<bool(int)>
auto mm = Creator(obj->shared_from_this(), &Obj::Meth1);
boost::function<bool (int)> mm2 = Creator2<int>(obj->shared_from_this(), &Obj::Meth1);
bool isSeven = mm(7);
cout << isSeven << endl;
cout << mm2(7) << endl;
return 0;
}