Aleksandr Safronov Asked:2024-11-28 16:10:57 +0000 UTC2024-11-28 16:10:57 +0000 UTC 2024-11-28 16:10:57 +0000 UTC 如果模板参数为 false,如何禁用模板类的 write[] 运算符? 772 有一个模板类实现了运算符[]。如果模板参数为 true,我想通过 [] 运算符将写权限设置为模板参数之一。并保存读取操作符。很明显,您可以在阅读时获取指针,但这已经是类用户的肮脏黑客行为,由他来决定。 如何实施? 准备考虑其他选择 c++ 1 个回答 Voted Best Answer sibedir 2024-11-28T18:18:22Z2024-11-28T18:18:22Z []您可以根据条件更改运算符的返回类型 #include <iostream> #include <type_traits> template <bool ReadOnly = false> class MyClass { private: int data[10] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 0 }; public: int const& operator[](size_t idx) const { return data[idx]; }; std::conditional_t<ReadOnly, int const&, int&> operator[](size_t idx) { return data[idx]; }; }; int main() { MyClass rw; std::cout << rw[5] << "\n"; rw[5] = 10; std::cout << rw[5] << "\n"; MyClass<true> ro; std::cout << ro[5] << "\n"; ro[5] = 10; // error std::cout << ro[5] << "\n"; } 那些。如果我们的类型是 readonly,它将operator[]返回常量值的左引用。
[]您可以根据条件更改运算符的返回类型那些。如果我们的类型是 readonly,它将
operator[]返回常量值的左引用。