2009-04-12 25 views
48

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

在这样的问题:Approaching STL algorithms, lambda, local classes and other approaches,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()); // error 
} 

有谁知道在标准是限制吗?禁止地方类型的理由是什么?


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

回答

50

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

C++ 11删除该限制。

为了更完整:

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

本地型,无键的类型, 未命名的类型或类型从任何这些类型的复合 不得使用 作为 模板类型参数的模板参数。

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

综上所述,限制是会被越早定,如果标准是不断变化的快了错误...

,今天说大多数最新版本的通用编译器都支持它,并提供lambda表达式。

+0

我知道,但我想知道在哪里可以看到我能理解为什么。你有没有参考标准? – 2009-04-12 23:16:57

+0

你是指14.3.1.2,“模板类型参数”? – greyfade 2009-04-12 23:19:12

5

该限制将在'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); }) 
} 

我在上面的语法可能不是完美的,但一般的概念是存在的。