c++ - 如何将 const 添加到 decltype(...) typedef?
问题描述
虽然我已经回顾了两个类似的问题,但考虑到这种 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
接受 consts 中的元素?好吧,我们应该从 vector::value_type 开始。还有其他方法吗?我也尝试在 typedef 中添加一个 const,但没有成功。
解决方案
推荐阅读
- oracle - Oracle Database 18c 配置助手失败
- node.js - Bazel Watcher 未终止节点进程(错误:监听 EADDRINUSE:地址已在使用 :::3000)
- python - 是否可以在 Python 中有单独的 lib 和 src 目录?
- sql - SQL Server 中多列的条件批量更新
- scrapy - 蜘蛛不会停止
- python-3.x - Python中的while循环程序用于存储可被10整除的值
- android - Lambda 不适用于 Kotlin 进行多线程操作
- spring - Spring - 通过 HttpSecurity 禁止除特定角色之外的所有端点
- javascript - Javascript 对象构造函数覆盖以停止调用某些方法
- swift - ARKit - 在 Motion Capture RealityKit 中复制机器人角色