c++ - decltype(function) 作为类成员

标签 c++ compiler-errors c++11 linker-errors decltype

我有:

int foo(int x) { return x+1; }

struct Bar {
  decltype(foo) operator();
};

int main() {
  Bar bar;
  printf("%d\n",bar(6));
}

这会导致稍微令人吃惊的编译器错误消息 (g++ 4.6.1):

error: declaration of 'operator()' as non-function

将成员名称更改为

  decltype(foo) blubb;

使用它会导致链接器错误:

undefined reference to `Bar::blubb(int)'

这是预期的行为吗?

最佳答案

您似乎想“复制”另一个函数的签名来创建具有相同签名的函数。因为 decltype(foo) 确实是函数的类型(而不是指向该函数的指针,它将是 decltype(&foo) 并且会导致指针声明) ,您可以使用它来声明一个与另一个函数具有相同签名的函数。

如链接器错误所示:

undefined reference to `Bar::blubb(int)'

这已经可以在您的编译器上正常工作了。然而,gcc 似乎还没有完全实现这部分标准,因为它不接受与函数调用运算符相同的语法。顺便说一句。会很高兴地接受它,然后链接会出错

undefined reference to `Bar::operator()(int)'

你关于为什么存在链接器错误的问题表明你误解了 decltype 的真正作用。

它只会评估一个类型,而不是更多。 blubb 的定义与 foo 的定义没有任何关系。这样写可能会更清楚

typedef decltype(foo) x; 
x blubb;

您现在可以选择将 typedef x 显式指定为函数类型,这不会以任何方式改变 blubb 是什么。您仍然需要定义它。由于没有使用 decltype 定义它的语法,因此您必须明确地将其写为

int Bar::operator()(int) {
...
}

这很可能并且不幸地破坏了使用 decltype 进行声明的目的/好处,因为它不允许您自动“复制”签名。

关于c++ - decltype(function) 作为类成员,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9326733/

相关文章:

C++ 错误 = "abs cannot be used as a function"(组类项目)

c++ - 该值被复制而不是被 move 。为什么?

c++ - 对 std::unordered_set 中元素的指针/引用

c++ - for循环中的Qt字符串生成器

linux - 当我尝试gcc make linux-headers -`uname -r`时遇到错误

compiler-errors - 从CLISP界面运行Common Lisp文件(错误)

c++ - std::map、std::set 和 std::priority_queue 中的比较器

python - 通过 C++ 的 RPC 启动新线程会导致进程僵尸化?

c++ - 为什么 auto_ptr 似乎违反了 Visual C++ 上的私有(private)继承?

c++ - O(log N) 查找和更新的数据结构,考虑到小型 L1 缓存