c++ - 如何实现 "const"和 "non-const"重载而不重复代码?

标签 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
}

附言

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/

相关文章:

c++ - 这里真的需要 sleep() 吗?

c++ - 范围解析运算符后的模板参数未被替换

c++ - 如何将 libfreenect 数据存储在点云中?

c++ - 如何检测类型是否为 std::tuple?

c++ - 表达式 : Invalid Operator < - Can't find the error

C++ urljoin 等效项

c++ - 专门用于枚举的模板

C++运算符重载(v << 1,2,3;)?

c++ - 在类似功能的 reduce 函数中转发和返回类型

c++ - 为什么放在双端队列类中的共享指针在初始化期间会发生读取访问冲突?