c++c++11user-defined-literals

Invoke user-defined literal on lvalue


Is there any way to invoke a user defined literal on lvalues?

e.g I would like to

int operator "" _xor1(int a) { return a^1; }

// Works fine
17_xor1;

auto myint = get_something_only_availabe_at_runtime();
// Any way to use _xor1 on myint?

_xor1(myint); // Doesn't work

Also, when compiling the following code at the compiler explorer, I was surprised to discover that it was all resolved at runtime, although all data is available at compile time. Why is that?

constexpr int operator "" _xor1(unsigned long long a) {
    return a^1; 
}

int main() {
    // This code resolves the user defined literal at runtime on gcc, 
    // msvc and clang - I don't see why I can't use the 
    // user defined literal at runtime?
    return 17_xor1;
}

Solution

  • I'm not sure you really want to - as commented, you're probably better off defining a normal function and calling that - but you can call it using:

    operator""_xor1(myInt);
    

    See User-defined literals for more information.