基类需要根据派生的特定类型返回自动类型

时间:2019-03-24 09:48:20

标签: c++ generics base-class

我想制作一个通用基类,用于将相同的Interface类存储在数组中。但是,泛型类应基于其派生类型返回特定于类型的变量。

我尝试了使用模板和类型推导的不同设计方法...还尝试将实际值存储在嵌套的类容器中。

我认为,我需要一种不同的方法来解决这个问题...但是我不知道什么对我有用。 任何设计的模式都可以解决此问题?

基类

class IAlpha
{
public:
    virtual auto Get() = 0;
};

派生类

template< typename T >
class Alpha:
    public IAlpha
{
    T x;
public:
    Alpha( T _x ):x(_x)
    {

    }

    auto Get() ->decltype(x) override
    {
        return x;
    }
};

主要

    IAlpha *i = new Alpha<int>(1);
    IAlpha *d = new Alpha<double>(1.0);


    int x = i->Get();
    double y = d->Get();

我在IAlpha :: Get()处遇到的错误 “推论返回类型的函数不能是虚拟的”

我了解问题所在,可以通过以下方式解决该问题

virtual auto Get()->decltype(  "TYPE"  ) = 0;

但是问题是接口不知道TYPE,因此不应保持其通用性。...

注意, 不幸的是,std::variantstd::any在我的应用程序中没有选项。

1 个答案:

答案 0 :(得分:0)

此解决方案并不理想...但是可以。

#include <iostream>
#include <assert.h>
#include <vector>

template< typename T >
class Param;

class IParam
{
protected:

public:

    template< typename T>
    const T& Get()
    {
        return static_cast< Param<T>* >(this)->Read();
    };
};


template< typename T >
class Param:
    public IParam
{
    T *x;
public:
    Param()
    {
        x = new T();
    }

    void Set( T _v)
    {
        *x = _v;
    }

    const T& Read()
    {
        return *x;
    }
};

// This vector will be a Singleton Parameter Manager
std::vector<IParam*> mParameters;

class Alpha
{
private:
    Param<int> *param;
public:
    Alpha()
    {
        param = new Param<int>();
        mParameters.push_back( param );
    }

    void Set()
    {
        param->Set(1);
    }
};

int main ()
{
    std::cout << "Starting Sandbox" << "\n";

    Alpha *a = new Alpha();

    // Attach to the Alpha parameter
    const int& i = mParameters[0]->Get<int>();

    // Print 0
    std::cout << i << std::endl;
    a->Set();

    // Print 1
    std::cout << i << std::endl;
    return 0;
}