gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 04:44:31 25 4
gpt4 key购买 nike

玩具示例:

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/

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