是否可以使用char字符串重载operator +?

时间:2016-03-02 16:06:21

标签: c++ string c++11 concatenation

我想简化java中字符串的使用。

所以我可以写"count "+6;并获得一个字符串"计数6" 使用std :: string,它可以用char字符串连接两个字符串或std :: string。

我写了两个函数

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;
}

将std :: string与数字连接起来,但是不能写"count "+6;之类的东西,因为"count "是一个const char []而不是一个std :: string。

它适用于std::string("count")+" is "+6+" and it works also with double "+1.234;,但那不是很漂亮=)

是否有可能在没有以std :: string开头的情况下做同样的事情(&#34;&#34;)

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

这种方法不起作用,我收到编译错误

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

2 个答案:

答案 0 :(得分:6)

没有。您不能为内置类型重载运算符;操作中涉及的两种类型之一必须是类类型或枚举。

通过使用用户定义的文字,你可以做些什么来使事情变得更加可口:

"count"s + 3.1415;

请注意,这是C ++ 14的一项功能,编译器可能支持也可能不支持。

答案 1 :(得分:3)

当重载运算符时,至少有一个操作数必须是用户类型(而std库中的类型被认为是用户类型)。换句话说:operator+的两个操作数都不能构建类型。

从C ++ 11开始,有文字运算符可用。他们可以写

"count "_s

而不是

std::string("count ")

这样的运算符是这样定义的(以下文字运算符的名称是_s;它们必须以自定义文字运算符重载的下划线开头):

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

然后,你的表达式变为

"count "_s + 6

在C ++ 14中,这样的运算符是already available,并且更方便地命名s(标准可以使用不带前导下划线的运算符名称),因此它变为

"count "s + 6