c++ - 具有常量和非常量值的映射

标签 c++ templates constants stdmap

我目前正在查看一些使用以下两种 map 类型实例的代码:

std::map<std::string, const Foo>;
std::map<std::string, Foo>;

Foo 的实现不相关。因此,所有将这两者之一的实例作为输入的函数都有它们的两个实现:一个用于 const Foo 版本,另一个用于非 const Foo 版本。

我的问题是:是否有可能使用模板创建一些东西(例如从 std::map 派生的类),这将允许我基本上封装上述类型的两个版本作为一个?

编辑:我知道我可能可以使用 SFINAE 只需要为每个相关函数编写一个版本,但我想知道是否有一种方法可以在“上游”进一步实现一些东西。

如果我的问题没有意义,我深表歉意 - 我不确定如何用合适的方式表达它。

最佳答案

可以通过这种方式实现可以接受 map 的 const 和非 const 版本的函数:

template <typename T_foo>
T_foo do_something_with_map(std::map<std::string, T_foo> & map)
{
    std::cout << map["m"].i_ << std::endl;
    return map["m"];
}

int main()
{
    std::map<std::string, const Foo> m1;
    Foo f1(1);
    m1.emplace("m", f1);

    std::map<std::string, Foo> m2;
    const Foo f2(2);
    m2.emplace("m", f2);

    auto res1 = do_something_with_map(m1);
    auto res2 = do_something_with_map(m2);
}

以 Foo 为例:

class Foo {
 public:
 Foo() = default;
 Foo(int i)
     : i_(i)
 {}
 int i_;
};

关于c++ - 具有常量和非常量值的映射,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51663316/

相关文章:

c++ - C++ 中的 std::vector 与 std::array

c++ - Qt - Visual Studio 中的 C++ 图形应用程序

c++ - const 函数最终通过友元类修改自身

c++ - Constexpr 这是正确的行为吗?

c++ - 分段故障多项式

c++ - 带有 std::bind 的 std::function<void()> 构造函数

c++ - 尝试与 typedef 交 friend 时出现 "elaborated type refers to typedef"错误

c++ - auto_ptr<T> 的模板特化

javascript - 自定义组件 - 如何克隆定义为 js 字符串文字的 html 模板?

c++ - 为什么我不能通过 const 指针修改变量?