c – 如何在没有重复代码的情况下实现“const”和“non-const”
发布时间:2020-12-16 09:56:12 所属栏目:百科 来源:网络整理
导读:template typename T,typename Predicate,typename Operationvoid Foo(T entity,Predicate pred,Operation op){ if (pred(entity)) { op(entity); } // and blah}template typename T,typename Operationvoid Foo(const T entity,Operation op){ if (pred(en
template <typename T,typename Predicate,typename Operation> void Foo(T& entity,Predicate pred,Operation op) { if (pred(entity)) { op(entity); } // and blah } template <typename T,typename Operation> void Foo(const T& entity,Operation op) { if (pred(entity)) { op(entity); } // and blah } 附: T&安培;实体pred(const T& entity)op(const T& entity)是可以接受的. const T&实体pred(T& entity)op(T& entity)应引发编译错误. 使用C 11的解决方案是可以的. 这里的例子: class MyEntity { public: MyEntity(int e):e(e){} int e; }; MyEntity a = 1234; MyEntity& ra = a; const MyEntity& cra = a; auto pred = [](const MyEntity& i) { return true; }; auto cop = [](const MyEntity& i) { cout<<i.e<<endl; }; auto op = [](MyEntity& i) { ++i.e; cout<<i.e<<endl; }; Foo(ra,pred,op); // ok Foo(ra,cop); // ok Foo(cra,cop); // ok Foo(cra,op); // error 解决方法
你可以只使用非const Foo,并将const验证留给特定的pred和op.
如果pred或op需要非const实体,并且实体是const(如示例代码中的第4次调用),编译器将抛出错误. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |