简体   繁体   中英

Possible to overload operator* to multiple an int and a char*?

I would like to get functionality so I can do this:

std::cout << "here's a message" << 5*"\n";

I tried the following:

std::string operator* (int lhs, const char* rhs) {
  std::string r = "";
  for(int i = 0; i < lhs; i++) {
    r += rhs;
  }
  return r;
}

And I got this error message:

error: ‘std::string operator*(int, const char*)’ must have an argument of class or enumerated type

According to the answers in this SO post What does 'must have an argument of class or enumerated type' actually mean it almost seems like I can't do this period. Is that really the case? If not, how do I fix this or arrange a workaround?

What I know I can do is have rhs as a std::string , but then the whole point of the exercise is half foregone, as 5*std::string("\\n") is quite clunky.

From [over.oper]:

An operator function shall either be a non-static member function or be a non-member function that has at least one parameter whose type is a class, a reference to a class, an enumeration, or a reference to an enumeration .

So you can't overload an operator whose parameters are both builtins. Furthermore, in order for operator*(int, std::string) to be found, it'd have to be in namespace std and it's ill-formed to add definitions to that namespace.

Instead, you could simply provide a small wrapper:

struct Mult { int value; };

and provide overloads for it:

std::string operator*(const Mult&, const char* );
std::string operator*(const char*, const Mult& );

From C++ FAQ here ,

C++ language requires that your operator overloads take at least one operand of a “class type” or enumeration type. The C++ language will not let you define an operator all of whose operands / parameters are of primitive types.

You neither can nor must overload that op;

string ctor (2) does the job for you

#include <iostream>
#include <string>

int main() {
    std::cout << "here's a message:\n" 
              << std::string(5, '\n') 
              << "EOF" << std::endl;
} 

output:

here's a message:






EOF

(live at Coliru)

You should be able to achive it with user-defined literals. For instance:

#include <iostream>
#include <string>


std::string operator"" _s(const char* s) { return std::string(s); }

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

std::string operator* (unsigned int k, std::string s) {
    std::string t;
    for (unsigned int i = 0; i < k; ++i) 
        t += s;

    return t;
}

std::string operator* (std::string s, unsigned int k) { return k * s; }

int main() {
    std::cout << "Jump!"_s * 5 << "\n";
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM