如何实现" const"和"非常数"重载没有重复的代码?

时间:2015-01-29 09:24:24

标签: c++ templates c++11 overloading

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
}

P.S。

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

2 个答案:

答案 0 :(得分:4)

您可以使用转发引用(又名"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
}

答案 1 :(得分:3)

您可以只使用非const Foo,并将const验证保留给特定的predop

如果predop要求非const entityentityconst(如示例代码中的第4次调用) ),编译器会抛出错误。