我编写了一个打印模板函数,它为 bool 类型值打印 "True"
或 "False"
。
我试图将它应用于 for_each
算法,但它不起作用。
输出仍然是0
或1
。似乎模板特化在 for_each
中不起作用。怎么会这样?
如何使代码按预期工作?
#include <iostream>
#include <vector>
#include <algorithm>
#include <numeric>
#include <ctime>
using namespace std;
template <typename T>
void _print(const T& i)
{
cout<<i<<endl;
}
template <>
void _print<bool>(const bool& i)
{
if (i == 0)
cout<<"False"<<endl;
else
cout<<"True"<<endl;
}
class print
{
public:
template <typename T>
void operator()(const T& val) const { _print(val); };
};
int main()
{
auto even = [&](int i)->bool{return (i%2==0);};
srand(time(NULL));
vector <int> test(3);
generate(test.begin(),test.end(),[]()->int{return rand()%100;});
for_each(test.begin(),test.end(),print());
vector <bool> flag(3);
transform(test.begin(),test.end(),flag.begin(),even);
for_each(flag.begin(),flag.end(),print());
return 0;
}
输出是:
34
23
3
1
0
0
但我希望:
34
23
3
True
False
False
最佳答案
std::vector<bool>
的邪恶部分| .
vector<bool>::reference
不是 bool
如您所料,只是一个代理。
您可以添加这个额外的重载(如果您愿意,也可以添加特化):
void _print(const vector<bool>::reference& i)
{
_print<bool>(i);
}
关于c++ - 为什么 for_each 不能在这里选择正确的打印,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25791719/