I recently gave an answer to this question on how to get Python-like string repeats, e.g. "hello" * 2
gives "hellohello"
.
I won't repeat the definition here, but the function declaration is:
std::string repeat(std::string str, const std::size_t n);
and can of course can be used like:
std::cout << repeat("helloworld", 2) << std::endl;
To get closer to the Python version, I thought I'd overload operator*
. Ideally I'd use a universal reference to avoid the additional std::string
move, but operators must use a user-defined type. So I tried this instead:
#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));
}
Now I can do this:
std::cout << (std::string("helloworld") * 2) << std::end;
and this:
std::cout << operator*("helloworld", 2) << std::endl;
but not this:
std::cout << ("helloworld" * 2) << std::endl;
// error: invalid operands to binary expression ('const char *' and 'int')
Why not?