简体   繁体   English

使用带有 STL 算法的本地类

[英]Using local classes with STL algorithms

I have always wondered why you cannot use locally defined classes as predicates to STL algorithms.我一直想知道为什么不能使用本地定义的类作为 STL 算法的谓词。

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 '在问题中: 接近 STL 算法、lambda、本地类和其他方法,BubbaT 提到“由于 C++ 标准禁止将本地类型用作参数

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.编辑:从 C++11 开始,使用本地类型作为模板参数是合法的。

It's explicitly forbidden by the C++98/03 standard. C++98/03 标准明确禁止这样做。

C++11 remove that restriction. C++11 移除了这个限制。

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: C++03 (和C++98)标准的第14.3.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.局部类型、没有链接的类型、未命名的类型或由这些类型中的任何一种复合的类型不应用作模板类型参数的模板参数。

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来源和更多详细信息: 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.也就是说,今天大多数最新版本的通用编译器确实允许它,同时提供 lambda 表达式。

The restriction will be removed in '0x, but I don't think you'll be using them very much.该限制将在 '0x 中删除,但我认为您不会经常使用它们。 And that's because C++-0x is going to have lambdas!那是因为 C++-0x 将有 lambdas! :) :)

int main() {
   int array[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
   std::vector<int> v( array, array+10 );

   std::remove_if( v.begin()
                 , v.end()
                 , [] (int x) -> bool { return !(x%2); })
}

My syntax in the above may be not be perfect, but the general idea is there.我上面的语法可能不完美,但大致思路就在那里。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM