问题描述
虽然我已经回顾了两个类似的问题,但鉴于 decltypes、references 和 consts 的这种组合,这些似乎没有帮助。
我想对结构的两个不同字段 field1
和 field2
运行一些测试。
一些代码:
#include <string>
#include <vector>
#include <functional>
#include <algorithm>
#include <memory>
struct my_structure
{
std::string field1;
std::string field2;
};
std::string calculate_pattern(const std::string& needle)
{
// Any silly thing instead of the real case
return needle + ".";
}
template <typename iterator>
bool some_function(iterator begin,iterator end)
{
typedef decltype(*begin) item_type;
// Can I add more consts? It looks like there are not enough of them!
std::vector< std::function<std::string& (const item_type &)> > cases;
cases.emplace_back([](const item_type& a) -> std::string& { return a->field1; });
cases.emplace_back([](const item_type& a) -> std::string& { return a->field2; });
/* const */ auto& item = *begin;
for (const std::function<std::string& (const item_type&)>& fn : cases)
{
const auto needle = fn(item); // FAILS: item is const,fn argument is not
auto result = std::find_if(begin,end,[&fn,&needle](/* const */ auto& a)
{
auto pattern = calculate_pattern(needle);
return fn(a) == pattern;
}
);
if (result != end)
return true;
}
return false;
}
#include <iostream>
using namespace std;
int main() {
std::vector<std::unique_ptr<my_structure> > v(3);
std::generate(v.begin(),v.end(),[]() {
return std::move(std::make_unique< my_structure>());
}
);
v[0]->field1 = "zz";
cout << some_function(v.begin(),v.end()) << endl;
return 0;
}
一旦任何已注释的 const
被取消注释,对 fn
的调用就会失败,表明其参数不是常量。
不要想太多逻辑(它总是返回false),它是从真实代码中简化出来的,因此可以编译。
是否有正确的方法来表示 cases
中的元素接受常量?好吧,我们应该从 vector::value_type 开始。还有其他方法吗?我也试过在 typedef 中放一个 const,但没有成功。
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)