Dan*_*iel 2 c++ string operators c++11
最近,我给了一个答案到这个问题,如何让Python的像串的重复,如"hello" * 2给"hellohello".
我不会在这里重复定义,但函数声明是:
std::string repeat(std::string str, const std::size_t n);
Run Code Online (Sandbox Code Playgroud)
当然可以像:
std::cout << repeat("helloworld", 2) << std::endl;
Run Code Online (Sandbox Code Playgroud)
为了更接近Python版本,我想我会超载operator*.理想情况下,我使用通用引用来避免额外的std::string移动,但运算符必须使用用户定义的类型.所以我尝试了这个:
#include <type_traits> // std::enable_if_t, std::is_integral
#include <utility> // std::move
template <typename T, typename = std::enable_if_t<std::is_integral<T>::value>>
std::string operator*(std::string str, const T n)
{
return repeat(std::move(str), static_cast<std::size_t>(n));
}
Run Code Online (Sandbox Code Playgroud)
现在我可以这样做:
std::cout << (std::string("helloworld") * 2) << std::end;
Run Code Online (Sandbox Code Playgroud)
还有这个:
std::cout << operator*("helloworld", 2) << std::endl;
Run Code Online (Sandbox Code Playgroud)
但不是这个:
std::cout << ("helloworld" * 2) << std::endl;
// error: invalid operands to binary expression ('const char *' and 'int')
Run Code Online (Sandbox Code Playgroud)
为什么不?
定义重载运算符时,至少有一个操作数必须是用户定义的类型.对于预定义类型,所有运算符都是预定义的,否则是禁止的.
当你明确地转换成std::string的string,需要一个构造函数char const *作为其参数/将用于文字转换为std::string,但是不,编译器不能/不会做转换.
同样,当您更明确地调用运算符时operator*("helloworld", 2),编译器"知道"它需要将字符串文字转换为重载所支持的类型operator *,因此它(基本上)枚举可以转换字符串文字的所有类型,然后看看它是否能找到operator *适合其中一种类型的东西.如果它找到多个,它确实(如果内存服务)候选operator *实现的正常重载决定以决定使用哪个.
string-literal * int但是,仅使用表达式,两种类型都是内置的,因此它只检查内置运算符.由于它们都不适合,因此禁止表达.
请注意,对于当前编译器,您可以使用s字符串文字的后缀来创建std::string:
#include <string>
std::cout << "helloworld"s * s << "\n";
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
101 次 |
| 最近记录: |