gpt4 book ai didi

c++ - 用户定义的文字可以有函数作为参数吗?

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:15:51 26 4
gpt4 key购买 nike

函数可以与用户定义的文字一起使用吗?

如果是这样,可以做什么恶作剧?这合法吗?

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,用户文字类型是整数文字、浮点文字、字符串文字和字 rune 字。没有办法做函数文字类型。

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.

整数:

operator "" X (n ULL)
operator "" X ("n")
operator "" X <’c1’, ’c2’, ... ’ck’>()

float :

operator "" X (f L)
operator "" X ("f")
operator "" X <’c1’, ’c2’, ... ’ck’>()

字符串:

operator "" X (str, len)
operator "" X <’c1’, ’c2’, ... ’ck’>() //unoffcial, a rumored GCC extension

字符:

operator "" X (ch)

关于c++ - 用户定义的文字可以有函数作为参数吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8100519/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com