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 Predicate, typename Operation>
void Foo(const T& entity, Predicate pred, Operation op)
{
if (pred(entity))
{
op(entity);
}
// and blah
}
附言
T& entity
+ pred(const T& entity)
+ op(const T& entity)
是可以接受的。
const T& entity
+ 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, pred, cop); // ok
Foo(cra, pred, cop); // ok
Foo(cra, pred, op); // error
最佳答案
您可以使用转发引用(又名 "universal reference" ):
template <typename T, typename Predicate, typename Operation>
void Foo(T&& entity, Predicate pred, Operation op)
{
if (pred(entity))
{
op(std::forward<T>(entity));
}
// and blah
}
关于c++ - 如何实现 "const"和 "non-const"重载而不重复代码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28211024/