【问题标题】:Taking the address of operator<< fails in gcc 4.8在 gcc 4.8 中获取 operator<< 的地址失败
【发布时间】:2016-06-21 21:53:57
【问题描述】:

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

【问题讨论】:

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


    【解决方案1】:

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

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

    Live Demo

    【讨论】:

    【解决方案2】:

    不要写ostream&amp;,而是写std::ostream&amp;:

    #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;
    }
    

    【讨论】:

    猜你喜欢
    • 2015-11-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-19
    相关资源
    最近更新 更多