在 C++ 中使用 void 指针返回多个类型变量的最佳方法是什么?

What is the best way to use void pointer for returning multiple type variables in C++?

我有这样的基础 class:

class Test {
public:
    virtual void* getValue () {}
};

然后我想创建几个实现 getValue 方法的派生 classes(它们将 return 将地址转换为 void* 后的不同类型变量):

class TestA : public Test {
private:
    int value;

public:
    TestA (int value) : value(value) {}

    void* getValue () {
        int* result = new int;
        *result = value;
        return (void*) result;
    }
};

在这种情况下,我正在创建要使用 "new" 编辑的变量 return,因此我必须在使用以下方法后将其删除:

    TestA testA(5);

    int* toDelete = (int*) testA.getValue();
    int someLocalVariable = *toDelete;
    delete toDelete;

我考虑过的第二种方法是创建一个 class 成员的副本,我想要 return 的值并将其仅用于 getValue() 方法:

class TestB : public Test {
private:
    double valToRet;
    double value;

public:
    TestB (double value) : value(value) {}

    void* getValue () {
        valToRet = value;
        return (void*) &valToRet;
    }
};

getValue() 方法的使用现在更简单了,但在那种情况下,每当我使用此方法时,我都会占用更多内存 class:

    TestB testB(3);

    double someOtherLocalVariable = *((double*)testB.getValue());

有没有更好的方法来实现 getValue() 方法? 我总是知道类型是什么,所以不用担心。

您可以将 Test class 包装在模板中。

template <typename T>
class Test {
public:
    virtual T* getValue () =0;
};

class TestA : public Test<int>
{
public:
    virtual int* getValue () { return new int(3); }
};

class TestB : public Test<float>
{
public:
    virtual float* getValue() { return new float(3.2); } 
};