【发布时间】:2015-01-29 09:24:23
【问题描述】:
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
【问题讨论】:
-
对于
T&和const T&,pred和op是否过载? -
@Bathsheba
pred和op应该遵循entity的常量,但不需要相同,例如我的T& entity和pred(const T& entity)示例。 -
我想,你所能做的就是在一个函数中编写 blah 代码。但问得好。
-
为什么需要非常量重载? IE。它有什么不同?
-
@SanderDeDycker 非 const 用于接受
T&的某些op,op可能会导致T& entity发生一些变化,所以我希望T& entity与 @ 987654343@(当然也可以使用op(const T& entity))。但是应该禁止相反的情况,即const T& entity和op(T& entity)。
标签: c++ templates c++11 overloading