小编ber*_*kus的帖子

多态运算符[]实现

让我们说我们有这个代码:

class test_t
{
    void* data;
public:
    template <typename T>
    T operator [](int index)
    {
        return reinterpret_cast<T*>(data)[index];
    }
};

int main()
{
    test_t test;
    int t = test.operator []<int>(5);
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

有没有办法将其转换为可编译的惯用C++?

应该是这样的

int main()
{
    test_t test;
    int t = test[5];
    double f = test[7];
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

即多态运算符[].

c++

6
推荐指数
1
解决办法
186
查看次数

标签 统计

c++ ×1