用户定义的文字可以将函数作为参数吗?
函数可以与用户定义的文字一起使用吗?
如果可以,可以做什么?这合法吗?
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
}
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
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
根据 C++11 Feb 2011 Draft § 2.14.8,用户文字类型为整型文字、浮点文字、字符串文字和字符文字。没有办法实现函数字面量类型。
整数:
浮点数:
字符串:
字符:
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.
Integers:
Floating:
String:
Character:
看看
foo_bar
,它只是一个词汇标记。它被解释为名为foo_bar
的单个标识符,而不是带有_bar
后缀的foo
。Look at
foo_bar
, its just a single lexical token. Its interpreted as a single identifier namedfoo_bar
, not asfoo
suffixed with_bar
.不会
。C++ 有意避免这种恶作剧,因为如果符号 foo_bar 在您的示例中使用之前没有立即定义,那么它会很难理解。
您可以使用预处理器实现类似的效果。
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.
我不知道这是否会增加任何内容,但没有什么可以阻止您定义
我实际上认为用户定义的文字将成为嵌入脚本或 SQL 的好方法。
I don't know if this adds anything but there's nothing preventing you from defining
I actually think user-defined literals would make a nice way to embed scripts or SQL.