c++ - 派生类中的成员字段别名(无访问函数)

标签 c++ c++17

玩具示例:

template<typename T, std::size_t N>
class static_vector
{
public:
    T& operator[](std::size_t i) { return m_elements[i]; }
    T const& operator[](std::size_t i) const { return m_elements[i]; }

private:
    std::array<T, N> m_elements;
};

template<typename T>
class vector3
    : public static_vector<T, 3>
{
public:
    using vector_type = static_vector<T, 3>;

//  x = vector_type::operator[](0);
//  y = vector_type::operator[](1);
//  z = vector_type::operator[](2);
};

vector3<float> pos; .我想访问 pos[0]通过pos.x .显然,如果 pos声明为 const , 我要 pos.x为只读。

这可能吗?

让我强调一下,我不想使用表单的访问器函数

T& x() { return (*this)[0]; }
T const& x() const { return (*this)[0]; }

最佳答案

没有零成本的方法可以使用您想要的确切语法来做到这一点。

放松成本(编译、维护、内存使用和运行时)或语法(您的 () 就是一个例子)可以得到您想要的。

关于c++ - 派生类中的成员字段别名(无访问函数),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49539778/

相关文章:

c++ - 基于组件的架构 C++

c++ - 函数参数前的类关键字是什么?

java - 一种算法,给出所有可能的不同数组,其正整数元素之和为给定数字

c++ - 为什么我的变体将 std::string 转换为 bool?

c++ - 有没有办法递归地使用类模板参数推导指南? (图灵完备了吗)

c# - 如何解码编码为 UTF8 的代理字符?

C++ : how can I fourier transform an array into an other array of different size using fftw3

c++ - 哪种处理虚拟析构函数的方法更好?

c++ - 类模板的嵌套模板参数推导不起作用

c++ - invoke_result with member (operator[]) 函数