运算符中的 lambda 出错<<具有默认参数的模板类
Error with lambda in operator<< of template class with default argument
有人能告诉我这个代码出了什么问题吗:
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错误57775。
正如@PiotrNycz所指出的,您可以通过将函数operator<<
的主体移动到类模板之外来解决问题。
相关文章:
- 如何反转整数参数包
- 使用C++库在Android项目中修改gradle中的cmake参数,用于插入指令的测试
- 如何使用默认参数等选择模板专业化
- 模板参数替换失败,并且未完成隐式转换
- 具有默认模板参数的多态类的模板推导失败
- lambda参数转换为constexpr技巧,然后获取带链接的数组
- 将数组作为参数传递给函数安全吗?作为第三方职能部门,可以探索他们想要的之外的其他元素
- 函数调用中参数的顺序重要吗
- 部分定义/别名模板模板参数
- 模板-模板参数推导:三个不同的编译器三种不同的行为
- 使用不带参数的函数访问结构元素
- 基于另一个成员参数将函数调用从类传递给它的一个成员
- 如何在OMNET++中指定与命令行参数组合的输出文件名
- 如何使用Luacneneneba API正确读取字符串和表参数
- 在派生函数中指定void*参数
- 视图中的参数推导失败:take_while
- 请解释这句话(cout<<1+int((a<b)^((b-a)&1) )<<endl
- 左角支架解释为操作员&lt;而不是模板参数
- 重载运算符<<:此运算符函数的参数太多
- 重载<<运算符错误C2804:二进制'运算符<<'参数太多