谁能告诉我这段代码出了什么问题:
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/