-1

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+'
too honest for this site
  • 11,797
  • 4
  • 29
  • 49
Morcl174
  • 93
  • 1
  • 9

2 Answers2

6

No. You cannot overload operators for built-in types only; one of the two types involved in the operation must either be a class type or an enumeration.

What you could do to make things more palatable is construct strings on the fly by using a user-defined literal:

"count"s + 3.1415;

Be aware that this is a C++14 feature that may or may not be supported by your compiler yet.

H. Guijt
  • 3,184
  • 10
  • 15
  • 3
    I clearly mentioned it is C++14. It does not invalidate the answer; it is an option the original poster may simply not be aware of. – H. Guijt Mar 02 '16 at 16:21
3

When overloading operators, at least one of the operands has to be a user type (while types from the std library are considered user types). In other words: Not both operands of operator+ can be builtin types.


Since C++11, there are literal operators available. They make it possible to write

"count "_s

instead of

std::string("count ")

Such an operator is defined like this (the name of the following literal operator is _s; they have to start with an underscore for custom literal operator overloads):

std::string operator ""_s(const char *str, std::size_t len) {
    return std::string(str, len);
}

Then, your expression becomes

"count "_s + 6

In C++14, such an operator is already available, and named more conveniently s (the standard may use operator names without a leading underscore), so it becomes

"count "s + 6
leemes
  • 43,629
  • 21
  • 127
  • 181