首页 > 解决方案 > 如何在不添加/删除 mem 函数的“const”的情况下重载 getter 函数?

问题描述

我想不通,为什么 C++ 不允许根据返回类型重载,因为在以下情况下,三个成员(getter)函数具有不同的函数签名,甚至何时存储指向成员函数的指针我们需要不同的 mem-函数指针类型如:

for instance T = std::string
using constRefPtr   = const std::string&(MyStruct::*)() const;
using constValuePtr = const std::string(MyStruct::*)() const;
using valuePtr      = std::string(MyStruct::*)() const;

我读过这篇类似的帖子,其中建议使用 const 和非成本成员函数。

问题:如何在不删除const每个成员函数的情况下使以下(getter)重载工作(如果可以通过标准 C++)?

我正在使用 C++17。

#include <iostream>
#include <string>

template<typename T> class MyStruct
{
    T m_val;
public: 
    explicit MyStruct(const T& value) 
        : m_val(value)
    {}
    const T& getVal() const {   return m_val; } // get val as const ref(no copy of member)
    const T getVal() const  {   return m_val; } // get a const member as return
    T getVal() const        {   return m_val; } // get a copy of member
};

int main()
{
    MyStruct<std::string> obj{"string"};
    const auto& val_const_ref = obj.getVal();  // overload const std::string& getVal() const
    const auto val_const = obj.getVal();       // overload const std::string getVal()  const
    auto val = obj.getVal();                   // overload std::string getVal()  const
    return 0;
}

我收到的错误消息:

error C2373 : 'MyStruct<T>::getVal' : redefinition; different type modifiers
note: see declaration of 'MyStruct<T>::getVal'
note: see reference to class template instantiation 'MyStruct<T>' being compiled
error C2059 : syntax error : 'return'
error C2238 : unexpected token(s) preceding ';'
error C2143 : syntax error : missing ';' before '}'
error C2556 : 'const T MyStruct<T>::getVal(void) const' : overloaded function differs only by return type from 'const T &MyStruct<T>::getVal(void) const'
1 > with
1 > [
    1 > T = std::string
        1 > ]
    1 > C:\Z Drive\CPP Programs\Visual Studio Project\Main.cc(62) : note: see declaration of 'MyStruct<std::string>::getVal'
note: see reference to class template instantiation 'MyStruct<std::string>' being compiled
error C2373 : 'MyStruct<std::string>::getVal' : redefinition; different type modifiers
note: see declaration of 'MyStruct<std::string>::getVal'
error C2059 : syntax error : 'return'
error C2238 : unexpected token(s) preceding ';'
error C2146 : syntax error : missing ';' before identifier 'T'
error C2530 : 'val_const_ref' : references must be initialized
error C2789 : 'val_const' : an object of const - qualified type must be initialized
note: see declaration of 'val_const'

标签: c++overloadingc++17member-functions

解决方案


你只是......不能重载返回类型,句号。

您可以创建两个不同命名的函数:

T const& ref() const { return m_val; }
T val() const        { return m_val; }

根据 ness 或 ness,它们本身可能会被重载const&

T const& ref() const { return m_val; }
T&       ref()       { return m_val; }

T val() const&       { return m_val; }
T val() &&           { return std::move(m_val); }

推荐阅读