Reputation:
I've found this example on cppreference.com:
// used as conversion
inline constexpr long double operator"" _deg ( long double deg )
{
return deg*3.141592/180;
}
...
double x = 90.0_deg; // x = 1.570796
But now I want to know, if I can give multiple arguments to that function. Here it is only deg
. I mean something like that: 0.3_arg1_21arg2
Upvotes: 3
Views: 478
Reputation: 545588
This feature does’t exist – but you can emulate it!
For instance, you can make the following syntax work:
auto result = 0.3_arg1/21_arg2;
The /
can be replaced by any overloadable operator of your choosing – maybe ,
would be a good choice, but beware of its low precedence. I would stick to something with a high precedence to ensure that this is parsed as if it were one literal (even though it isn’t).
Then, to make this work, you’d implement something like this (compiled in my brain only, so no guarantee of correctness):
struct value_proxy_lhs { double d; };
struct value_proxy_rhs { double d; };
struct final_value { double a; double b; };
inline constexpr value_proxy_lhs operator ""_arg1(double d) { return {d}; }
inline constexpr value_proxy_rhs operator ""_arg2(double d) { return {d}; }
inline constexpr final_value operator /(value_proxy_lhs lhs, value_proxy_rhs rhs) {
return {lhs.d, rhs.d};
}
In a proper application you’d probably hide the value_proxy_*
classes as much as possible from the users so that they cannot accidentally produce incomplete values. – Unfortunately, I don’t think there’s a way of avoiding this completely. For instance, the language simply doesn’t offer a way of forbidding something like auto x{1_arg1};
to compile, as far as I know. Making the copy constructor private
(and final_value
a friend
) would probably make the proxy classes non-POD and thus forbid using them as constexpr
(AFAIR).
As a real-world application I could imagine a date “literal”:
auto date = 2013_yy/12_mm/07_dd;
Upvotes: 7
Reputation: 249153
No, there is no such feature. Sorry to be the bearer of bad news!
Upvotes: 0