Search code examples
c++c++11user-defined-literals

Can user defined literals have functions as arguments?


Can functions be used with user defined literals?

If so, what shenanigans can be done? Is this legal?

void operator "" _bar(int (*func)(int)) {
  func(1);
}

int foo(int x) {
  std::cout << x << std::endl;
}

int main() {
  foo(0);    // print 0
  foo_bar;   // print 1
}

Solution

  • According to the C++11 Feb 2011 Draft § 2.14.8, the user literal types are integer-literals, floating-literals, string-literals, and character-literals. There is no way to do a function-literal type.

    A user-defined-literal is treated as a call to a literal operator or literal operator template (13.5.8). To determine the form of this call for a given user-defined-literal L with ud-suffix X, the literal-operator-id whose literal suffix identifier is X is looked up in the context of L using the rules for unqualified name lookup (3.4.1). Let S be the set of declarations found by this lookup. S shall not be empty.

    Integers:

    operator "" X (n ULL)
    operator "" X ("n")
    operator "" X <’c1’, ’c2’, ... ’ck’>()
    

    Floating:

    operator "" X (f L)
    operator "" X ("f")
    operator "" X <’c1’, ’c2’, ... ’ck’>()
    

    String:

    operator "" X (str, len)
    operator "" X <’c1’, ’c2’, ... ’ck’>() //unoffcial, a rumored GCC extension
    

    Character:

    operator "" X (ch)