2

I tried implicit conversion, but this doesn't work.

#include <string>
#include <iostream>

struct MyClass
{
    operator std::string() { return "bar"; }
};

int
main( int argc, char* argv[] )
{
    MyClass x;

    std::cout << std::string( "foo" ) + x << std::endl;
    return 0;
}
kfmfe04
  • 14,936
  • 14
  • 74
  • 140

3 Answers3

4

Implicit conversion won't work since string's operator+ is templated and you're deducing the template parameters. This looks like a better explanation of what's happening: https://stackoverflow.com/a/8892794/964135

I would just do a cast or write a non-template operator+.


A stupid solution is to not deduce the types and then it will do the implicit conversion:

std::cout << std::operator+<char, std::char_traits<char>, std::allocator<char> >(std::string( "foo" ), x) << std::endl;
Community
  • 1
  • 1
Pubby
  • 51,882
  • 13
  • 139
  • 180
2

Have you tried overloading the + operator?

std::string operator+(std::string& str, MyClass& x){
    return str + "bar"
} 

This would be a free function, not part of MyClass. Also, it might be necessary to overload the commutative case as well. You can express it in terms of the above one if it doesnt matter.

Karthik T
  • 31,456
  • 5
  • 68
  • 87
1

To the nice answers given by Karthik T and Pubby regarding overloaded operator+(), I would like to add one point.

Usually you would need to access private members of the MyClass inside the overloaded operator+() code (unlike the return "bar"; as in your presumably stripped down example). In that case, you would need to declare it as a friend. You cannot have the operator+() as a member of MyClass, because the MyClass comes on the left side of the operator +. Refer below sample code.

#include <string>
#include <iostream>
using namespace std;

struct MyClass {
public:
    MyClass() : bar("bar") {}
    friend string operator+(string& str, MyClass& x);
private:
    string bar;
};

string operator+(string& str, MyClass& x) {
    return str + x.bar;
}

int main( int argc, char* argv[] )
{
    MyClass x;
    string foo("foo");

    std::cout <<  foo + x << std::endl;
    return 0;
}
Masked Man
  • 1
  • 7
  • 40
  • 80