0

I would like to know what are the main differences between the following methods. Is there a case were one of the two would cause problems if std::to_string is defined?

include <string>
using namespace std;


enum class eColor
{
   Red
};

void to_string(eColor color)
{
}

template<typename C = eColor)
void to_string(C color)
{
}



int main()
{
   to_string(eColor::Red); // assume only one of the above is defined
   return 0;
}

Is there a case where one of the above should be preferred?

Nick
  • 10,309
  • 21
  • 97
  • 201

2 Answers2

1

Your function to_string(eColor color) is not really a template specialization because it misses template<> before definition. So the compiler treats it as a fully defined function, not a template to be generated with a concrete type. That means this function will always be used as long the compiler can match the argument list.

JPX
  • 93
  • 1
  • 4
0

Despite things like the unnecessary pollution of the name space by your using directive which is especially weird if you plan on using names like to_string:

Template functions automatically deduce their template argument. So the following would be absolutely valid:

int main(int argc, const char * argv[]) {
    to_string(eColor::Red);
    to_string("Hey");
    to_string(42);
    return 0;
}

So if you really plan to taylor your function for one dedicated type you are in for some really interesting error messages or even worse no error messages combined with unwanted behavior.

The function version will a least prevent some of the erroneous cases. (It will still accept the 42 though since there is an implicit conversion).

DrSvanHay
  • 1,170
  • 6
  • 16