为什么使用本地结构作为 STL 函数参数的代码不能在 g++ 中编译?
我有这样的代码,效果很好:
#include <algorithm>
#include <iostream>
char x[11]= "ABCDEFGHIJ";
char y[11];
struct F {
char operator () (char c) const
{ return c+1; }
};
int main()
{
std::transform(x, x+10, y, F());
y[10] = 0; std::cout <<y <<std::endl;
}
但是如果我将其更改为这种样式:
#include <algorithm>
#include <iostream>
char x[11]= "ABCDEFGHIJ";
char y[11];
int main()
{
struct F {
char operator () (char c) const
{ return c+1; }
};
std::transform(x, x+10, y, F());
y[10] = 0; std::cout <<y <<std::endl;
}
它将无法编译,并说:
错误:没有匹配的函数可用于调用“transform(char [11], char*, char [11], main()::F)”
出了什么问题?
gcc 版本是 4.4,它不识别 lambda 表达式。
I have such code which works well:
#include <algorithm>
#include <iostream>
char x[11]= "ABCDEFGHIJ";
char y[11];
struct F {
char operator () (char c) const
{ return c+1; }
};
int main()
{
std::transform(x, x+10, y, F());
y[10] = 0; std::cout <<y <<std::endl;
}
But if I change it to this style:
#include <algorithm>
#include <iostream>
char x[11]= "ABCDEFGHIJ";
char y[11];
int main()
{
struct F {
char operator () (char c) const
{ return c+1; }
};
std::transform(x, x+10, y, F());
y[10] = 0; std::cout <<y <<std::endl;
}
It will not compile, saying:
error: no matching function for call to ‘transform(char [11], char*, char [11], main()::F)’
What's wrong?
gcc version is 4.4, which does not recognize lambda expressions.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
在 C++-98/03 中,第二个代码无效,因为 F 是局部类型;事实上,第 14.3.1.2 节指出
在 C++-0x 中,此限制被删除;在同一部分中,新标准草案(N3126)在示例中明确表明了这一点:
In C++-98/03 the second code is not valid, since F is a local type; in facts, at §14.3.1.2 it's stated that
In C++-0x this limitation is removed; in the same section, the new standard draft (N3126) explicitly shows this in the example:
g++ 4.5.1 编译代码(使用
-std=c++0x
选项) 。您的第二个代码示例在 C++031 中格式不正确,但在 C++0x
std::transform
中有效,但是 g++ 4.4 不支持本地类型作为模板参数(即使使用 -
std=c++0x
option] 所以你会得到一个错误1 :本地类型、没有链接的类型、未命名类型或由任何这些类型组合而成的类型不得用作模板类型的模板参数 -参数(ISO C++03 §14.3.1.2)
g++ 4.5.1 compiles your code (with
-std=c++0x
option).Your second code sample is ill-formed in C++031 but valid in C++0x
std::transform
isHowever g++ 4.4 doesn't support local types as template arguments (even with -
std=c++0x
option] so you get an error.1 : A local type, a type with no linkage, an unnamed type or a type compounded from any of these types shall not be used as a template-argument for a template type-parameter. (ISO C++03 §14.3.1.2)