2

I am a beginner in template programming and I am using the following template function trying to avoid code duplication:

template <class T>
void foo(T iInteger) {

    // ... same algorithm for all integer types

    std::to_string( static_cast<T>(iInteger) ); // C2668: ambiguous call to overloaded function

    // ... end of algorithm

}

My foo function will be called only with primitive integral types. I was naively thinking that static_cast would have been enough to tell the compiler which overload of std::to_string() to use, but this seems not enough as im still getting a C2668: ambiguous call to overloaded function. What am I missing? Is it possible to avoid duplicating the same code for all primitive integer types while still calling the appropriate std::to_string overload?

Andrea Casaccia
  • 4,802
  • 4
  • 29
  • 54
  • 2
    What are you passing in as a template argument? I recall having this problem with MSVS, but not GCC, as MSVS had only implemented half of the options. You can look in the header you have and see for yourself what they made available in there. – chris Sep 08 '12 at 23:20
  • I am using it for the primitive integer types so long, int, short and their unsigned versions. – Andrea Casaccia Sep 08 '12 at 23:24
  • I see that std::to_string doesn't have all the overloads I expected, it has only long long, or unsigned long long. I guess that is the problem... Is that correct @chris? – Andrea Casaccia Sep 08 '12 at 23:29
  • 1
    Yes, that's the one I ran into. From looking, VS11 seems to have the `int` etc. versions. I didn't check whether they were all there, though, but I presume they are now. I guess you could circumvent it by converting the type to `long long`, `unsigned long long`, `long double`, or `unsigned long double` depending on whether it's `std::is_integral` and `std::is_signed`. – chris Sep 08 '12 at 23:31
  • 1
    @chris would you like to elaborate an answer? Otherwise I can do it. BTW I found that this question already explains the problem: http://stackoverflow.com/questions/10664699/stdto-string-more-than-instance-of-overloaded-function-matches-the-argument – Andrea Casaccia Sep 08 '12 at 23:53
  • Ah, if you've found a duplicate, it's probably best to stick to that. However, the duplicate doesn't deal with templates at all, so you can post your working code to have a genuine template solution. – chris Sep 08 '12 at 23:55

1 Answers1

2

As pointed out by chris in the comments to the question, the problem is that I'm using VS2010, which does not fully implement the c++11 standard. std::to_string implements only overloads for long long, unsigned long long, long double. See this related question for more details on the matter.

Community
  • 1
  • 1
Andrea Casaccia
  • 4,802
  • 4
  • 29
  • 54