【问题标题】:Base class needs to return auto-type based on derived specific type基类需要根据派生的特定类型返回自动类型
【发布时间】:2019-08-14 18:59:18
【问题描述】:

我想创建一个通用基类,用于在数组中存储相同的接口类。但是,泛型类应该根据它的派生返回一个特定于类型的变量。

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

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

基类

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;

但问题是接口不知道类型,它不应该保持它是通用的......

注意, std::variant & std::any 很遗憾在我的应用程序中没有选项。

【问题讨论】:

  • 您的目标不符合LSP
  • @Ron 你可能也对curiously recurring template pattern感兴趣。
  • @RonSalm 这表明你的类架构存在严重的设计缺陷。可能只是缺少另一个级别的间接性。您应该阅读@StoryTeller 发布的链接。
  • @Hemil,界面中Get之类的虚函数不能是模板。
  • @RonSalm 拿到intdouble 后,你会如何处理它们?那将是我要看的第一个地方。如果您可以概括该部分,您可能根本不需要知道 IAlpha 中包含的类型。

标签: c++ generics base-class


【解决方案1】:

这个解决方案并不理想......但它会做。

#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;
}

【讨论】:

  • 结合了Hemil的提议和πάνταῥεῖ的提议,
猜你喜欢
  • 1970-01-01
  • 2018-10-10
  • 1970-01-01
  • 2012-09-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-07-31
  • 1970-01-01
相关资源
最近更新 更多