I could not figure this out, why C++ is not allowing overloading according to the return type as in the following case the three member(getter) function has different function signature and even when to store the pointer to the member function we need different mem-function pointer types like:
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;
I have read this similar post, where it was suggestion to have const and non-cost member functions.
Question: How could I make the following (getter)overloads work without removing const
ness
of each member functions(if it is possible through standard C++)?
I am using 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 messages I have got:
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'