c++ - 带有默认参数的模板类的 operator<< 中的 lambda 错误

标签 c++

谁能告诉我这段代码出了什么问题:

template<typename B=int> // <<<< =int is provoking the error
struct Foo
{
    std::array<B,10> data;

    template<typename F>
    void iterate(F f) const
    {
        for(unsigned i=0; i<10; i++) {
            f(i, data[i]);
        }
    }

    friend std::ostream& operator<<(std::ostream& os, const Foo<B>& a) // Line 17
    {
        a.iterate([&os](unsigned i, const B& x) {
            os << i << "=" << x << "\n";
        });
        return os;
    }
};

GCC 4.8.1 和 --std=c++11 的错误消息:

test.cpp: In function ‘std::ostream& operator<<(std::ostream&, const Foo<B>&)’:
test.cpp:17:41: error: default argument for template parameter for class enclosing ‘operator<<(std::ostream&, const Foo<B>&)::__lambda0’
   a.iterate([&os](unsigned i, const B& x) {

最佳答案

a.iterate([&os](unsigned i, const B& x) {
    os << i << "=" << x << "\n";
});

此处引入的 lambda 函数具有在 operator<< 函数范围内声明一个“未命名”局部类的效果。函数体。我们可以编写自己的仿函数对象来获得类似的效果:

struct lambda {
    std::ostream& os;

    lambda(std::ostream& os_) : os(os_) {}

    void operator()(unsigned i, const B& x) {
        os << i << "=" << x << "\n";
    }
};
a.iterate(lambda(os));

这从 g++ 中引发了类似的错误:

error: default argument for template parameter for class enclosing
       ‘operator<<(std::ostream&, const Foo<B>&)::lambda::lambda’

这是一个 SSCCE:

template <typename T = int>
struct Foo
{
    friend void f() {
        struct local {};
    }
};

及其引发的错误:

error: default argument for template parameter for class enclosing
       ‘f()::local::local’

这已被报告为 GCC bug 57775 .

正如@PiotrNycz 所指出的,您可以通过移动函数的主体来变通 operator<<在类模板之外。

关于c++ - 带有默认参数的模板类的 operator<< 中的 lambda 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23181238/

相关文章:

c++ - 有什么方法可以安全地处理两次通过 delete-expression 释放内存?

c++ - 使用 mongo-cxx-driver 构建 C++ 项目时出现链接错误

c++ - 如果缩小转换是可能的,则强制转换和失败编译

c++ - 我的 Floyd-Warshall C++ 实现中的错误

c++ - c++项目中TagLib的安装与使用

c++ - 定时器上的Arduino PID

c++ - 在 if 条件下检测 "="而不是 "=="拼写错误

c++ - 在 ImageMagick 中创建具有字符特定颜色的文本标签

c++ - std::bad_alloc 不进入交换空间

c++ - 在 OpenCV 中使用时间进行帧处理和其他任务