c – 带有默认参数的模板类的operator <<中的lambda出错
发布时间:2020-12-16 07:08:34 所属栏目:百科 来源:网络整理
导读:有人可以告诉我这段代码出了什么问题: templatetypename B=int // =int is provoking the errorstruct Foo{ std::arrayB,10 data; templatetypename F void iterate(F f) const { for(unsigned i=0; i10; i++) { f(i,data[i]); } } friend std::ostream ope
|
有人可以告诉我这段代码出了什么问题:
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函数具有在运算符中的函数范围内声明“未命名”本地类的效果<<功能体.我们可以编写自己的仿函数对象来获得类似的效果: 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所指出的,你可以通过移动函数运算符的主体<<在课堂模板之外. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
