FAQ 23.10 Can a operator serve as an exponentiation operator?

FAQ 23.10 Can a ** operator serve as an exponentiation operator?

No, it can't.

The names, precedence, associativity, and arity (number of arguments) of operators are predefined by the language. There is no ** operator in the C++ language, and it is not possible to add the ** operator to the C++ language.

In fact, the expression x ** y is already syntactically legal C++. It means, x * (*y) (that is, y is treated like a pointer that is dereferenced). If C++ allowed users to provide new meaning to **, the compiler's lexical analyzer (the lowest-level operation in the compiler) would need to be contextually dependent on the semantic analyzer (the highest-level operation in the compiler). This would probably introduce ambiguities and break existing code.

Operator overloading is merely syntactic sugar for function calls. Although syntactic sugar is sweet, it is not fundamentally necessary. Raising a number to a power is best performed by overloading pow(base, exponent), a double precision version of which can be found in the <cmath> header file.

Another candidate for an exponentiation operator is operator^, but it has neither the proper precedence nor the proper associativity.

Don't force-fit the semantics of an overloaded operator.



C++ FAQs
C Programming FAQs: Frequently Asked Questions
ISBN: 0201845199
EAN: 2147483647
Year: 2005
Pages: 566
Authors: Steve Summit

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net