gpt4 book ai didi

c++ - 在同一类模板中存储常量或非常量引用

转载 作者:行者123 更新时间:2023-12-01 22:04:01 24 4
gpt4 key购买 nike

下面的例子是退化的,因为我想了解这个概念。

假设我们想要一个数组的 1 元素 View

我的问题是如何使其适用于 const非 const 对象。

我知道为什么下面代码中的第二个 block 无法编译,但我不知道如何组织代码来服务这两种情况。

#include <cassert>
#include <array>

template <typename T>
class View {
private:
const std::size_t index_;
T &t_;
using value_type = typename T::value_type;

public:
View(T &t, std::size_t index) : t_{t}, index_{index} {}

const value_type &value() const { return t_[index_]; }
value_type &value() { return t_[index_]; }
};

int main() {
using Array = std::array<int, 2>;

// The block below works
{
Array array{0, 0};
View<Array> view(array, 0);
view.value() = 5;
assert(array[0] == 5);
}

// The block below gives a compilation error
{
const Array array{5, 5};
View<Array> view(array, 0);
assert(view.value() == 5);
}
}

最佳答案

以下作品:

#include <cassert>
#include <array>

template <typename T>
class View {
private:
using value_type = typename T::value_type;

T &t_;
const std::size_t index_;

public:
View(T &t, std::size_t index) : t_{t}, index_{index} {}

const value_type &value() const { return t_[index_]; }

template<class Arr = T, class = typename std::enable_if<!std::is_const<Arr>::value>::type>
value_type &value() { return t_[index_]; }
};

int main() {
using Array = std::array<int, 2>;

// The block below works
{
Array array{0, 0};
View<Array> view(array, 0);
view.value() = 5;
assert(array[0] == 5);
}

// The block below gives a compilation error
{
const Array array{5, 5};
View<const Array> view(array, 0);
assert(view.value() == 5);
}
}

如果您给出View一个const Array您还必须指定 const Array作为模板参数。

但随后返回一个非 const引用value()不再起作用了,所以如果数组类型是const,我们用SFINAE禁用这个功能。 .

PS:如果你的类名为View,你就不会遇到最后一个问题。确实是人们在 View 下所期望的,即不可修改,甚至没有返回非 const 的方法。引用。

关于c++ - 在同一类模板中存储常量或非常量引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59758720/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com