测试代码:
template<typename T>
void test() {
T container { 1, 2, 3 };
std::for_each(container.begin(), container.end(), [](int v) {
cout<<"1st for_each"<<endl;
});
cout<<"xxxxxx"<<endl;
std::for_each(container.begin(), container.end(), [](typename T::value_type v) {
cout<<"2nd for_each"<<endl;
});
}
int main() {
test<vector<int>>();
return 0;
}
请注意,我在不同的 lambda 中使用int i
和typename T::value_type v
param 类型。
编译命令:clang++ -std=c++11 -stdlib=libc++ test.cpp -o test
clang 版本 3.1 (branches/release_31) 目标:i386-pc-linux-gnu 线程模型:posix
结果:
2nd for_each
2nd for_each
2nd for_each
xxxxxx
2nd for_each
2nd for_each
2nd for_each
问题是:为什么要先for_each
打印出“2nd for_each”?
编辑:它可能是一个 clang++ 错误。
@KennyTM 给出了类似的更简单的代码:
#include <iostream>
using namespace std;
template<typename T>
void test() {
([](int v) { printf("1\n"); })(3);
([](T v) { printf("2\n"); })(4);
}
int main() {
test<int>();
return 0;
}
结果:
1
1