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

查看:12
本文介绍了使用带有 STL 算法的本地类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直想知道为什么不能使用本地定义的类作为 STL 算法的谓词.

I have always wondered why you cannot use locally defined classes as predicates to STL algorithms.

在问题中:接近STL算法,lambda,本地类和其他方法,BubbaT 提到由于 C++ 标准禁止将本地类型用作参数"

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'

示例代码:

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?

编辑:从 C++11 开始,使用本地类型作为模板参数是合法的.

EDIT: Since C++11, it is legal to use a local type as a template argument.

推荐答案

C++98/03 标准明确禁止这样做.

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

C++11 移除了这个限制.

C++11 remove that restriction.

为了更完整:

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

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 }

来源和更多详细信息: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...

也就是说,今天大多数最新版本的通用编译器确实允许这样做,并提供 lambda 表达式.

That said today most last versions of common compilers does allow it, along with providing lambda expressions.

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

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