c++ - const重载而不必写两次函数

标签 c++ constants overloading

<分区>

Possible Duplicate:
Elegant solution to duplicate, const and non-const, getters?

假设我有一个带有成员函数的 C++ 类,它为 const 重载,如下所示:

        Type*  DoSomething();
const   Type*  DoSomething() const;

如果这是一个更大、更复杂的成员,如何避免必须两次编写相同的代码?不能从常量函数调用任何非常量函数。从非 const 调用 const 版本会导致 const 指针必须转换为非 const(imo 有点味道)。

最佳答案

您可以委托(delegate)给模板静态成员函数,如:

class Widget
{
    Type member;

    template<typename Result, typename T>
    static Result DoSomethingImpl(T This)
    {
        // all the complexity sits here, calculating offsets into an array, etc
        return &This->member;
    }

public:
            Type*  DoSomething() { return DoSomethingImpl<Type*>(this); }
    const   Type*  DoSomething() const { return DoSomethingImpl<const Type*>(this); }
};

在 C++11 中,您甚至可以通过以下方式摆脱非推断模板参数:

static auto DoSomethingImpl(T This) -> decltype(This->member)

关于c++ - const重载而不必写两次函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11655852/

相关文章:

具有方法重写的 C++ 继承

c++ - 常量的拷贝?

c++ - GCC 6.3.0 中的 ODR 违规,类型定义在两个单独的翻译单元中

c++ - 我在 C++ 中的 http 服务器没有正确发送回所有文件

c++ - 从信号处理程序打印堆栈跟踪

ruby - 为什么不能在 Ruby 的方法中声明常量?

C++:返回类成员变量地址时,编译器强制为const *类型

java - DAO 方法约定 - 重载或更改方法名称?

c++ - 为非数组重载 std::begin() 和 std::end()

C++ 揭秘第 13 章 (2004) Jeff Kent : Ifstream program does not return expected output