使用本地类与STL算法 [英] Using local classes with STL algorithms

查看:170
本文介绍了使用本地类与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; //错误:指向用作模板参数的本地类型的指针}

源和更多详细信息: http://www.informit.com/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 : 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.

这篇关于使用本地类与STL算法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆