将本地类与 STL 算法结合使用
我一直想知道为什么不能使用本地定义的类作为 STL 算法的谓词。
在问题中:接近STL算法,lambda,本地类和其他方法,BubbaT 提到“由于 C++ 标准禁止将本地类型用作参数”
示例代码:
int main() {
int array[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
std::vector<int> v( array, array+10 );
struct even : public std::unary_function<int,bool>
{
bool operator()( int x ) { return !( x % 2 ); }
};
std::remove_if( v.begin(), v.end(), even() ); // error
}
有谁知道标准中的限制在哪里? 不允许本地类型的理由是什么?
编辑:从 C++11 开始,使用本地类型作为模板参数是合法的。
I have always wondered why you cannot use locally defined classes as predicates to STL algorithms.
In the question: Approaching STL algorithms, lambda, local classes and other approaches, BubbaT mentions says that 'Since the C++ standard forbids local types to be used as arguments'
Example code:
int main() {
int array[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
std::vector<int> v( array, array+10 );
struct even : public std::unary_function<int,bool>
{
bool operator()( int x ) { return !( x % 2 ); }
};
std::remove_if( v.begin(), v.end(), even() ); // error
}
Does anyone know where in the standard is the restriction? What is the rationale for disallowing local types?
EDIT: Since C++11, it is legal to use a local type as a template argument.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
C++98/03 标准明确禁止它。
C++11 删除了该限制。
为了更完整:
来源和更多详细信息:http://www.informit.com/ guides/content.aspx?g=cplusplus&seqNum=420
总而言之,这个限制是一个错误,如果标准发展得更快的话,这个错误就会被更快修复……
也就是说,今天常见编译器的最新版本确实允许这样做,并提供 lambda 表达式。
It's explicitly forbidden by the C++98/03 standard.
C++11 remove that restriction.
To be more complete :
Source and more details : http://www.informit.com/guides/content.aspx?g=cplusplus&seqNum=420
To sum up, the restriction was a mistake that would have been fixed sooner if the standard was evolving faster...
That said today most last versions of common compilers does allow it, along with providing lambda expressions.
该限制将在 '0x 中被删除,但我认为您不会经常使用它们。 那是因为 C++-0x 将有 lambda! :)
我上面的语法可能并不完美,但总体思路是这样的。
The restriction will be removed in '0x, but I don't think you'll be using them very much. And that's because C++-0x is going to have lambdas! :)
My syntax in the above may be not be perfect, but the general idea is there.