首页 > 解决方案 > 如何将 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,但没有成功。

标签: c++templatesstd-functiondecltype

解决方案


推荐阅读