Greetings,
I've got a class that stores its value as a std::string. This value can be set using a public accessor method that is templated and overloaded to accept many different inputs. The generic 'set' template method takes in ints, shorts, floats, etc, passes the value through a std::stringstream for conversion, then stores the value as a string. I have a couple specialized versions of the 'set' method which handle input that the stringstream cannot. This all works fine.
My problem comes with the 'get' method. Originally, my 'get' method required the caller to pass by reference a parameter into the function to know what type to convert to. It looks like:
<type> value;
instance.get(value);
This again allowed me to use specialized methods for the types that stringstream can't convert to. However, it felt cumbersome to have to first declare a variable and then pass it into the 'get' method. I then thought about how would look to have the 'get' method simply return the appropriate type and look like:
<type> value = instance.get<type>();
This works fine for many cases, expect for the specialized ones. I have 2 specializations of the 'set' method, but when I try to declare the specializations of the 'get' method using my new scheme, the compiler errors out saying that the two functions only differ by return types. In other words, I have:
template <typename T>
T get()
{
std::stringstream s;
s << m_String.c_str();
double temp = 0.0f;
s >> temp;
return static_cast<T>(temp);
}
std::string get()
{
return m_String;
}
MyClass get()
{
MyClass instance;
instance.set_text(m_String);
// More happens, but I think you get the picture.
return MyClass;
}
Is there no way to tell the compiler which version of 'get' (std::string or MyClass) to use? I am able to do it for the template types, why not these other two? (in other words,
unsigned int value = instance.get<unsigned int>(); // works
float value_2 = instance.get<float>(); // works
std::string value_3 = instance.get<std::string>(); // fails!