函数可以与用户定义的文字一起使用吗?
如果是这样,可以做些什么恶作剧?这合法吗?
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
}
函数可以与用户定义的文字一起使用吗?
如果是这样,可以做些什么恶作剧?这合法吗?
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
}
根据 C++11 Feb 2011 Draft § 2.14.8,用户文字类型是整数文字、浮动文字、字符串文字和字符文字。没有办法做一个函数文字类型。
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)
看foo_bar
,它只是一个词法标记。它被解释为一个名为 的标识符foo_bar
,而不是foo
后缀_bar
.
不。
C++ 有意避免这种恶作剧,因为如果符号 foo_bar 没有在您的示例中使用之前立即定义,则将很难理解。
您可以使用预处理器实现类似的效果。
#define bar (1)
int foo(int x) {
std::cout << x << std::endl;
}
int main() {
foo(0); // print 0
foo bar; // print 1
}
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.