Can user literals function as arguments?

Can functions be used with user-defined literals?

If so, what fraud can be done? Is it 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 } 
+4
source share
4 answers

According to the C ++ project of February 11, 2011, Β§ 2.14.8, user types are integer literals, floating literals, string literals and character literals. Cannot execute function type literal.

A user literal is considered as a call to a literal operator or a literal operator pattern (13.5.8). To determine the form of this call for a given user literal L with ud-suffix X, literal-operator-id, whose literal suffix identifier is X, is looked up in context L using the rules for finding unqualified names (3.4.1). Let S be the set of ads found by this search. S should not be empty.

Whole numbers:

 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) 
+7
source

Take a look at foo_bar , it's just a lexical token. It is interpreted as a single identifier named foo_bar , and not as foo , a suffix with _bar .

+1
source

No.

C ++ deliberately avoids such fraud, since the foo_bar symbol will be very difficult to understand if it was not defined immediately before using it in your example.

You can achieve something similar with a preprocessor.

 #define bar (1) int foo(int x) { std::cout << x << std::endl; } int main() { foo(0); // print 0 foo bar; // print 1 } 
+1
source

I don’t know if this adds something, but nothing prevents you from determining

 PythonScript operator"" _python(const char*, std::size_t len) {...} R"Py( print "Hello, World" )Py"_python; 

I actually think custom literals would make a good way to embed scripts or SQL.

+1
source

Source: https://habr.com/ru/post/1380854/


All Articles