4

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

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

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

4 回答 4

7

根据 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’&gt;()

Floating:

operator "" X (f L)
operator "" X ("f")
operator "" X <’c1’, ’c2’, ... ’ck’&gt;()

String:

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

Character:

operator "" X (ch)
于 2011-11-11T22:10:38.667 回答
1

foo_bar,它只是一个词法标记。它被解释为一个名为 的标识符foo_bar,而不是foo后缀_bar.

于 2011-11-11T22:04:43.523 回答
1

不。

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
}
于 2011-11-11T22:09:07.410 回答
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.

于 2012-01-15T03:17:11.400 回答