Thread: How define template with "exception" cases?

  1. #1
    Registered User
    Join Date
    Nov 2006
    Posts
    184

    How define template with "exception" cases?

    I have a template function that works for 99% of the cases and want a different one for the 1%. The problem is that the template case is too "vague" and thus the compiler tries to use it for everything.

    Code:
    template <typename T> T get(T a)
    {
        ...
    }
    
    //The one case I want diff.
    std::string get(SomeClass a)
    {
     ...
    }
    
    int main()
    {
        std::string name( "Jeff" );
    
        //This is correct
        std::string val = get( name );
    
        SomeClass a;
    
        //Won't compile, says:
        //cannot convert 'SomeClass' to 'std::string' in initialization
        std::string val = get( a );
    }

  2. #2
    and the hat of sweating
    Join Date
    Aug 2007
    Location
    Toronto, ON
    Posts
    3,545

  3. #3

  4. #4
    Registered User
    Join Date
    Nov 2006
    Posts
    184
    Quote Originally Posted by medievalelks View Post
    But that doesn't work. it just tells me that the specializing template does not match any template declaration.

    I think it's because the original template declaration takes and returns the same type and the specialization takes and returns different types. Any ideas?

  5. #5
    The larch
    Join Date
    May 2006
    Posts
    3,573
    This actually works for me as long as the second version indeed returns a string and not a SomeClass.
    Code:
    #include <iostream>
    #include <string>
    
    class SomeClass
    {
    };
    
    template <typename T> T get(T a)
    {
        std::cout << "Template\n";
        return a;
    }
    
    //The one case I want diff.
    std::string get(SomeClass a)
    {
        std::cout << "String_get\n";
        return "String";
        //return a;
    }
    
    int main()
    {
        std::string name( "Jeff" );
    
        //This is correct
        std::string val = get( name );
    
        SomeClass a;
    
        std::string val2 = get( a );
    }
    I might be wrong.

    Thank you, anon. You sure know how to recognize different types of trees from quite a long way away.
    Quoted more than 1000 times (I hope).

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. size of an integer pointer
    By onebrother in forum C Programming
    Replies: 5
    Last Post: 07-09-2008, 11:49 AM
  2. Would someone solve my problem?
    By Lonners in forum C Programming
    Replies: 9
    Last Post: 01-19-2008, 06:58 PM
  3. Bor to DevC++ prog convert prob
    By kryptkat in forum Windows Programming
    Replies: 16
    Last Post: 09-18-2007, 05:11 AM
  4. Error check problem again
    By rtransfi in forum C Programming
    Replies: 6
    Last Post: 02-27-2003, 04:55 PM
  5. float toolbar!
    By c-- in forum Windows Programming
    Replies: 5
    Last Post: 02-04-2003, 09:44 AM