大佬教程收集整理的这篇文章主要介绍了一个Functor在C中永远不会是抽象的吗?,大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
#include <vector> #include <algorithm> class Functor { public: virtual bool operator()(int a,int b) const = 0; }; class MyFunctor: public Functor { public: virtual bool operator()(int a,int b) const { return true; } }; int _tmain(int argc,_TCHAR* argv[]) { vector<Functor> fv; // template of abstract class is possible vector<int> v; MyFunctor* mf = new MyFunctor(); sort(v.begin(),v.end(),*mf); Functor* f = new MyFunctor(); // following line does not compile: // "CAnnot have a parameter of the abstract class Functor" sort(v.begin(),*f); return 0; }
现在,我想知道这是否是函子参数的一般属性,还是它依赖于STL实现?有办法获得,我想做什么?
更新:感谢@ahenderson和@ltjax的评论,这里有一个非常简单的方法来生成一个保存原始多态引用的包装器对象:
#include <functional> std::sort(v.begin(),std::ref(*f)); // ^^^^^^^^^^^^
std :: ref的结果是std :: refrence_wrapper,它正是您所需要的:具有值语义的类,它包含对原始对象的引用.
仿函数被复制的事实抛弃了许多想要在仿函数中积累某些东西的人,然后想知道为什么结果是关闭的.仿函数应该真正引用外部对象.以机智:
坏!不会像你期望的那样工作;仿函数可以任意复制:
struct Func1 { int i; Func1() : i(0) { } void operator()(T const & X) { /* ... */ } }; Func1 f; MyAlgo(myContainer,f);
好:你提供累加器;复制仿函数是安全的:
struct Func2 { int & i; Func2(int & n) : i(n) { } void operator()(T const & X) { /* ... */ } }; int result; MyAlgo(myContainer,Func2(result));
以上是大佬教程为你收集整理的一个Functor在C中永远不会是抽象的吗?全部内容,希望文章能够帮你解决一个Functor在C中永远不会是抽象的吗?所遇到的程序开发问题。
如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。