On 21.02.2016 00:31, Stefan Ram wrote:
> #include <iostream>
> constexpr double operator "" ²( long double const d ){ return d*d; }
> int main(){ ::std::cout << 3.00² << '\n'; }
> [Error] stray '\262' in program
>
> Alas, the compiler is right.
No, it isn't.
Standard C++ allows the full set of Unicode "identifier" characters just
as in other languages, but the g++ compiler supports only ASCII.
However, the program should not compile because you need an underscore
between `""` and `²`, otherwise the name is /reserved/.
> Still, it would have been nice, if
> the program would just have printed »9«. What's working is:
>
> #include <iostream>
> constexpr double operator "" _2( long double const d ){ return d*d; }
> int main(){ ::std::cout << 3.00_2 << '\n'; }
Or you can do this:
#include <iostream>
constexpr auto operator""_²( long double const d )
-> long double
{ return d*d; }
auto main() -> int { std::cout << 3.00_² << '\n'; }
Except for the non-conforming behavior of g++, of course. <g/>
> The following also does not work:
>
> #include <iostream>
> #include <cmath>
>
> constexpr double operator ^
> ( double const x, double const y )
> { return ::std::pow(x,y); }
>
> int main(){ ::std::cout << 3.00 ^ 2.00 << '\n'; }
>
> Of course, the compiler is right, but the committee could have
> said: Ok, we reserve »^« for integral types, but the user can
> overload it for floating-point types. (It still would not have
> the right priority and associativity.)
I think the language design here is about the best possible, given the
requirement to support C as a subset.
It makes sense to not be able to redefine the meaning of operators for
built-in types.
But if you're willing to accept some quirks, you can define a
pseudo-operator like `%ᛏ%` (it gets the precedence etc. of `%`):
#include <iostream>
#include <math.h> // ::pow
struct Power_op {};
const Power_op ᛏ; // Runic letter Tîwaz Týr, U+16CF
struct Power_base { double const value; };
auto operator%( double const base, Power_op const )
-> Power_base
{ return {base}; }
auto operator%( Power_base const base, double const exponent )
-> double
{ return ::pow( base.value, exponent ); }
auto main() -> int
{
::std::cout << 3 %ᛏ% 2 << '\n';
}
Of course, as before, the g++ non-conforming character set limitation
means that it won't work with that compiler without preprocessing.
I didn't make those operators `constexpr` because `::pow` isn't.
Cheers & hth.,
- Alf