具有模板成员变量的 C++ 类

标签 c++ templates types

我正在尝试解决一个由包含多个参数的对象(称为图表)组成的编程问题。每个参数(Parameter 类)可以是以下几种类型之一:int、double、complex、string - 仅举几例。

所以我的第一直觉是将我的 Diagram 类定义为具有模板参数的 vector ,如下所示。

class Diagram
{
private:
    std::vector<Parameter<T> > v;
};

这不能编译,我明白为什么。因此,根据此页面上的建议 How to declare data members that are objects of any type in a class ,我修改我的代码看起来像:

class ParameterBase
{
public:
    virtual void setValue() = 0;
    virtual ~ParameterBase() { }
};


template <typename T>
class Parameter : public ParameterBase
{
public:
    void setValue() // I want this to be 
                    // void setValue(const T & val)
    {
        // I want this to be 
        // value = val;
    }

private:
    T value;
};

class Diagram
{
public:
    std::vector<ParameterBase *> v;
    int type;
};

我无法弄清楚如何使用适当的模板化参数调用 setValue 函数。在 ParameterBase 抽象基类中不可能有模板化参数。非常感谢任何帮助。

附:我没有使用 boost::any 的灵 active 。

最佳答案

你已经很接近了。我添加了一些位,因为它们很方便

class ParameterBase
{
public:
    virtual ~ParameterBase() {}
    template<class T> const T& get() const; //to be implimented after Parameter
    template<class T, class U> void setValue(const U& rhs); //to be implimented after Parameter
};

template <typename T>
class Parameter : public ParameterBase
{
public:
    Parameter(const T& rhs) :value(rhs) {}
    const T& get() const {return value;}
    void setValue(const T& rhs) {value=rhs;}    
private:
    T value;
};

//Here's the trick: dynamic_cast rather than virtual
template<class T> const T& ParameterBase::get() const
{ return dynamic_cast<const Parameter<T>&>(*this).get(); }
template<class T, class U> void ParameterBase::setValue(const U& rhs)
{ return dynamic_cast<Parameter<T>&>(*this).setValue(rhs); }

class Diagram
{
public:
    std::vector<ParameterBase*> v;
    int type;
};

然后,Diagram 可以执行以下操作:

Parameter<std::string> p1("Hello");
v.push_back(&p1);
std::cout << v[0]->get<std::string>(); //read the string
v[0]->set<std::string>("BANANA"); //set the string to something else
v[0]->get<int>(); //throws a std::bad_cast exception

看起来您的意图是将拥有资源的指针存储在 vector 中。如果是这样,请注意使 Diagram 具有正确的析构函数,并使其不可复制构造和不可复制分配。

关于具有模板成员变量的 C++ 类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13980157/

相关文章:

javascript - 将 Javascript 放入 CSS

c++ - 如何在函数模板中获得不同类型

c++ - 这是错误的警告吗?

python - 在 python 中检查变量是否为数字类型的最佳方法是什么

haskell - 为什么类型安全的关系操作如此困难?

具有相同名称但参数不同的 C++ 方法

c++ - 将 double 列表规范化为范围 -1 到 1 或 0 - 255

c++ - 在 Flex 中包含外部头文件

c# - 为混合平台(32、64)编译并引用在运行时解析的 32 或 64 位 DLL

arrays - Ada 中无约束可变类型的数组