How to fix this "Call of overloaded function is ambiguous" error?

I have the following simple code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
template<class T> class myClass{

   void print(string s){
      //something
   }

   void print(T t){
      //something else
   }

}
...
int main(){

   myClass x;
   x.print("this doesn't work");

   return 0;
}


I basically want to do something if the function parameter is a string, and something else if it is anything else. How can I do this? Thanks!
Last edited on
@keskiverto I can't figure out how to make it work :(
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
#include <string>
#include <iostream>

struct some_class {

    // overload for std::string
    void print( std::string ) const { std::cout << "print std string\n" ; }

    template < typename T > // overload for all other types
    void print(T) const { std::cout << "print something else\n" ; }
};

template < typename T > struct another_class {

    // overload for std::string
    void print( std::string ) const { std::cout << "print std string\n" ; }

    // overload for T
    void print(T) const { std::cout << "print T\n" ; }

    template < typename U > // overload for all other types
    void print(U) const { std::cout << "print something else\n" ; }
};

int main() {

    some_class x ;
    x.print( "abcd" ) ; // print something else (const char*)
    x.print( std::string("abcd") ) ; // print std string
    x.print(1234.5) ; // print something else (double)

    std::cout << '\n' ;

    another_class<double> y ;
    y.print( "abcd" ) ; // print something else (const char*)
    y.print( std::string("abcd") ) ; // print std string
    y.print(1234.5) ; // print T (double)
    y.print(123) ; // print something else (int)
}

http://coliru.stacked-crooked.com/a/4b6ab144d3db8863
Topic archived. No new replies allowed.