c++ - 在 gcc 4.8 中获取 operator<< 的地址失败

标签 c++ c++11 gcc template-meta-programming

我正在尝试编写一个特征来检测任意类型是否具有为其定义的插入运算符。为此,我希望使用 std::is_same<> 将函数指针的类型与预期类型进行比较。我有以下代码显示的问题

#include <iostream>
class A {};
std::ostream& operator<<(std::ostream& os, const A& a)
{
  return os;
}
int main()
{
  decltype(static_cast<std::ostream&(*)(ostream&, const A&)>(&operator<< )) foo = nullptr;
  std::cout << foo << std::endl;
  return 0;
}

在 gcc 4.8 中使用 --std=c++11

test2.cpp:12:81: error: expected primary-expression before ')' token
  decltype(static_cast<std::ostream&(*)(std::ostream&, const A&)>(&::operator<< )) foo = nullptr;
                                                                                 ^ 

该错误不会出现在 clang 或更新版本的 gcc 中,但是对于生产,我们必须能够在 gcc 4.8 中编译。 GCC 4.8 中是否有解决方法?

最佳答案

看起来那个版本的 GCC 没有正确解析它。要解决此问题,您可以为函数指针类型声明一个别名:

using op_type = std::ostream&(*)(std::ostream&, const A&);
decltype(static_cast<op_type>(&operator<< )) foo = nullptr;

Live Demo

关于c++ - 在 gcc 4.8 中获取 operator<< 的地址失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37946109/

相关文章:

c++ - 在 C 中垂直打印字节数组

c++ - 是否可以将 `B<get_item<0,Ts...>>` 更改为 `template_with_params<B, 1, ...Ts>` ?

c++ - 正则表达式匹配数字的重复模式,后跟任何类型的定界符?

c++ - clang++ 3.3 静态分析器,如何消除误报?

c - 什么会导致 gcc 部分编译 C 代码?

python - 编译时出现 GCC 错误 : cc1 out of memory error

c++ - 替代数组表示

c++ - 什么 C++11 <atomic> 操作/内存顺序保证新鲜度?

c++ - 如何在窗口中显示文件夹中所有文件的名称? Qt C++

gcc - C 预处理器添加了自己的注释