mercredi 2 mars 2016

Is it possible to overload the operator + with char strings?

I want to simplify the using of strings like in java.

so i can write "count "+6; and get a string "count 6" with std::string it's possible to concatenate two strings or std::string with char string.

i wrote 2 functions

template<typename T>
inline static std::string operator+(const std::string str, const T gen){
    return str + std::to_string(gen);
}

template<typename T>
inline static std::string operator+(const T gen, const std::string str){
    return std::to_string(gen) + str;
}

to concatenate std::string with numbers, but cannot write something like "count "+6; because "count " is a const char[] and not a std::string.

it works with std::string("count")+" is "+6+" and it works also with double "+1.234; , but thats not really pretty =)

is there a possibility to do the same without starting with std::string("")

template<typename T>
inline static std::string operator+(const char* str, const T gen){
    return str + std::to_string(gen);
} 

this method doesn't work and i get an compiler error

error: invalid operands of types 'const char*' and 'const char [1]' to binary 'operator+'

Aucun commentaire:

Enregistrer un commentaire