如果我知道如何提取匹配类型,是否有一种现代的表达方式来表示有条件地从不同类型的源容器复制到目标容器?
更容易的方法是通过代码示例提出问题:
#include <algorithm>
#include <vector>
struct Foo {};
struct FooBar{
bool is_valid;
Foo foo;
};
std::vector<Foo> get_valid_foos(const std::vector<FooBar>& foobars){
std::vector<Foo> valid_foos;
for(const auto& fbar : foobars){
if(fbar.is_valid)
valid_foos.push_back(fbar.foo);
}
return valid_foos;
}
std::vector<Foo> get_valid_foos_modern(const std::vector<FooBar>& foobars){
std::vector<Foo> valid_foos;
std::copy_if(foobars.begin(), foobars.end(), std::back_inserter(valid_foos),
[](const auto& foobar){
return foobar.is_valid;
});
//?? std::copy requires input and output types to match
return valid_foos;
}
std :: transform_if
,但如果您愿意使用库,有几个库可以实现此功能。 - Justinstd::copy_if
将正常工作。 - Pete Beckerstatic_cast<float>()
。 - MSalters