Pubby
Pubby

Reputation: 53017

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
}

Upvotes: 4

Views: 292

Answers (4)

emsr
emsr

Reputation: 16333

I don't know if this adds anything but there's nothing preventing you from defining

PythonScript operator"" _python(const char*, std::size_t len) {...}

R"Py(
  print "Hello, World"
)Py"_python;

I actually think user-defined literals would make a nice way to embed scripts or SQL.

Upvotes: 1

Mooing Duck
Mooing Duck

Reputation: 66912

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)

Upvotes: 7

Drew Dormann
Drew Dormann

Reputation: 63704

No.

C++ intentionally avoids such shenanigans since the symbol foo_bar would be very difficult to comprehend if it weren't defined immediately before its use in your example.

You could achieve something similar with the preprocessor.

#define bar (1)

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

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

Upvotes: 1

K-ballo
K-ballo

Reputation: 81349

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.

Upvotes: 1

Related Questions