简体   繁体   中英

In C++, how do I use symbol «×» instead of «*» for multiplication? Preprocessor and operator overloading are of no help for this

I hate when asterisk symbol is used for multiplication. It is ugly, and looks like pointer dereference operator.

I tried to use preprocessor:

#define × *

But the compiler says that «Macro name must be an identifier». What do I do?

Let me preface this answer with a recommendation to never do this.


Given your title, yes this is somewhat possible:

template <typename T>
struct Y {
    T const& i;
    friend auto operator>>(Y y, T const& j) {
        return y.i * j;
    }
};
struct X {
    template <typename T>
    friend auto operator<<(T const& i, X) {
        return Y<T>{i};
    }
};
inline X x;

This will allow multiplications of the form operandA <<x>> operandB :

#include <iostream>

int main() {
    std::cout << (6 <<x>> 7) << "\n"; // prints 42
}

The operator overloads are optimised out by the compiler , but it will most decidedly not be optimised out by any human brain reading your code. Don't do this.

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