Thread: Overload conversion operator from outside class...

  1. #1
    Not stupid, just stupider yaya's Avatar
    Join Date
    May 2007
    Location
    Earthland
    Posts
    204

    Thumbs up Overload conversion operator from outside class...

    I wan't to convert an std::string to a std::wstring. To make things easier, I want to overload the conversion operator to make it more simplified but I don't want to encapsulate in my own class. Here's sort of how I'd imagine it to be implemented:

    Code:
    operator std::wstring( std::string a )
    {
    	std::wstring b;
    
    	// conversion code here
    
    	return b;
    }
    ...so then I can do something like this:

    Code:
    std::string Text( "This is text." );
    std::wstring WideText = Text;
    Obviously, my attempt failed. But is this even possible?

    Thanks.

  2. #2
    The larch
    Join Date
    May 2006
    Posts
    3,573
    Have you considered a named free function? Implicit is not always good.

    Code:
    std::string Text( "This is text." );
    std::wstring WideText = widen(Text);
    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).

  3. #3
    Not stupid, just stupider yaya's Avatar
    Join Date
    May 2007
    Location
    Earthland
    Posts
    204
    Do you mean like this?:

    std::wstring Convert( std::string )

    If so, I something like this right now, though it can get a bit messy when you start using it a fair bit. I was just looking into an alternative.

  4. #4
    The larch
    Join Date
    May 2006
    Posts
    3,573
    The cast operator can't be overloaded as a free function (thank god!).

    I don't understand why things would get messy. You get to read code that tells you what is going on, rather than having things going on invisibly with types where you absolutely won't suspect anything.
    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).

  5. #5
    Not stupid, just stupider yaya's Avatar
    Join Date
    May 2007
    Location
    Earthland
    Posts
    204
    Yes, I see your point. Thanks for your help.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Whats the best way to control a global class?
    By parad0x13 in forum C++ Programming
    Replies: 3
    Last Post: 11-12-2009, 05:17 PM
  2. Default class template problem
    By Elysia in forum C++ Programming
    Replies: 5
    Last Post: 07-11-2008, 08:44 AM
  3. Dikumud
    By maxorator in forum C++ Programming
    Replies: 1
    Last Post: 10-01-2005, 06:39 AM
  4. structure vs class
    By sana in forum C++ Programming
    Replies: 13
    Last Post: 12-02-2002, 07:18 AM