使用STLalgorithm的本地类

我一直想知道为什么你不能使用本地定义的类作为STLalgorithm的谓词。

在这个问题: 接近STLalgorithm,lambda,本地类和其他方法 ,BubbaT提到说:“ 由于C ++标准禁止本地types作为参数

示例代码:

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 } 

有谁知道标准在哪里是限制? 禁止地方types的理由是什么?


编辑 :由于C ++ 11,使用本地types作为模板参数是合法的。

它明确地被C ++ 98/03标准所禁止。

C ++ 11删除了这个限制。

要更完整:

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

一个本地types,一个没有链接的types,一个未命名的types,或者任何这些types复合的types都不能被用作模板types参数的模板参数。

 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

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

也就是说今天大多数最新版本的通用编译器都支持它,并提供lambdaexpression式。

这个限制将在'0x'中被删除,但是我不认为你会非常使用它们。 这是因为C ++ – 0x将有lambda! 🙂

 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); }) } 

我上面的语法可能并不完美,但总体思路是存在的。