使用本地类与STL算法

编程入门 行业动态 更新时间:2024-10-26 02:30:57
本文介绍了使用本地类与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()); //错误}

有谁知道标准中的哪里是限制?

编辑:自从C ++ 11之后,使用本地类型作为模板参数是合法的。

解决方案

它是明确禁止的C ++ 98/03标准。

$ b

更完整:

在第14.3.1节中列出了用作模板参数的类型的限制 的C ++ 03 (和 C ++ 98)标准:

本地类型,没有链接的类型,一个未命名类型或一个类型复合从任何这些类型不应该是用作模板类型参数的模板参数。

模板< class T>类Y {/ * ... * /}; void func(){ struct S {/ * ... * /}; // local class Y< S> y1; // error:local type used as template-argument Y< S *> y2; //错误:指向用作模板参数的本地类型的指针}

源和更多详细信息: www.informit/guides/content.aspx?g=cplusplus&seqNum= 420

总而言之,这个限制是一个错误,如果标准发展得更快,那么这个限制就会被修复...

今天说的最常见的编译器版本允许它,并提供lambda表达式。

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.

解决方案

It's explicitly forbidden by the C++98/03 standard.

C++11 remove that restriction.

To be more complete :

The restrictions on types that are used as template parameters are listed in article 14.3.1 of the C++03 (and C++98) standard:

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.

template <class T> class Y { /* ... */ }; void func() { struct S { /* ... */ }; //local class Y< S > y1; // error: local type used as template-argument Y< S* > y2; // error: pointer to local type used as template-argument }

Source and more details : www.informit/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.

更多推荐

使用本地类与STL算法

本文发布于:2023-11-29 03:29:57,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1645100.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:算法   STL

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!