Dav*_*eas 50 c++ stl stl-algorithm
我一直想知道为什么你不能使用本地定义的类作为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() ); // error
}
Run Code Online (Sandbox Code Playgroud)
有谁知道标准中的限制在哪里?禁止当地类型的理由是什么?
编辑:从C++ 11开始,使用本地类型作为模板参数是合法的.
Kla*_*aim 53
它被C++ 98/03标准明确禁止.
C++ 11删除了这个限制.
更完整:
C++ 03(和C++ 98)标准的第14.3.1节列出了 对用作模板参数的类型的限制:
本地类型,没有链接的类型,未命名的类型或从这些类型中的任何类型复合的类型不应该用作模板类型参数的模板参数.
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 }
Run Code Online (Sandbox Code Playgroud)
来源和更多详情:http://www.informit.com/guides/content.aspx?g = cplusplus&seqNum = 420
总而言之,限制是一个错误,如果标准发展得更快,这个错误就会很快得到修复......
那就是说今天大多数常见编译器的版本都允许它,同时提供lambda表达式.
限制将在'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); })
}
Run Code Online (Sandbox Code Playgroud)
我在上面的语法可能并不完美,但总体思路就在那里.
| 归档时间: |
|
| 查看次数: |
5645 次 |
| 最近记录: |