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

Taking the address of operator<< fails in gcc 4.8

我正在尝试编写一个特征来检测任意类型是否具有为其定义的插入运算符。为此,我希望使用 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

而不是 ostream&,写 std::ostream&:

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