Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
}
like image 551
Pubby Avatar asked Dec 28 '22 11:12

Pubby


2 Answers

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)
like image 181
Mooing Duck Avatar answered Jan 30 '23 13:01

Mooing Duck


Look at foo_bar, its just a single lexical token. Its interpreted as a single identifier named foo_bar, not as foo suffixed with _bar.

like image 28
K-ballo Avatar answered Jan 30 '23 13:01

K-ballo