模板类的载体 [英] Vector of template class

查看:66
本文介绍了模板类的载体的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

(我已经阅读了一些有关此问题的现有问题,它们似乎略有不同,并且对我而言并没有使问题更清楚.)

(I've read several existing questions regarding this issue and they seem slightly different and don't make the issue any clearer to me.)

我正在尝试创建一个键-值对的向量,其中的值是通用的. 逻辑上指示我需要的代码如下:

I'm trying to create a vector of key-value pairs in which the value is generic. The code which logically indicates what I need follows:

#include <stdio.h>
#include <string.h>
#include <vector>

template <typename T>
class CCmd
{
    protected:
        char name[64];
        T value;

    public:
        CCmd(char* _name, T _value)
        {
            strcpy(name, _name);
            value = _value;
        }

        T getValue()
        {
            return value;
        }

        void setValue(T _value)
        {
            value = _value;
        }
};

int main()
{
    std::vector<CCmd*> vec;

    vec.push_back(new CCmd<int>("gravity", 150));
    vec.push_back(new CCmd<char*>("configfile", "config.cfg"));

    printf("Value = %d\n", vec[0]->getValue());
    printf("Config = %s\n", vec[1]->getValue());

    return EXIT_SUCCESS;
}

这不能以我认为在语法上正确的所有方式进行编译.我读了一个问题,即需要使用基类来封装通用类,但是我尝试通过创建一个空类(如图所示)并使它成为它的子类来对此进行尝试:

This fails to compile in every way I think it would be syntactically correct. I read on one question that using a base class to encapsulate the generic class is required, however I tried this by creating an empty class as indicated and made my generic class a subclass of it:

...
class CCmdBase
{
};

class CCmd : public CCmdBase
{
...

并且编译器抱怨CCmdBase没有名为getValue的成员,鉴于它返回通用类型T,这意味着基类也需要通用,以便我在其中定义它在那里,这意味着我回到了开始的地方?

and the compiler complains that CCmdBase doesn't have a member named getValue which, given that it returns the generic type T, would mean that the base class would also need to be generic for me to define it in there, which means that I'm back where I'm started?

请帮助;我在这里想念什么?

Please help; what am I missing here?

推荐答案

您的方法无法在C ++中轻松完成.您的设计很可能是不正确的,应该加以改进.很难建议确切的方法,但是可能的解决方案是使用具有纯虚函数的抽象基类.尽管您的虚拟函数在当前的设计"中不能为setValuegetValue,因为函数签名必须与虚拟函数匹配.

Your approach cannot be easily done in C++. Most probably your design is incorrect and should be improved. It is difficult to advise exact way, but possible solution to have abstract base class with pure virtual functions. Though your virtual function cannot be setValue or getValue in your current "design" as function signature must match for virtual functions.

如果确实需要在向量中实现具有不同值的方法,请查看std::tupleboost::variantboost::any.同样,不要指望这种解决方案的使用对您来说将是容易理解和直接的.

In case you really need to implement approach with different values in the vector look into std::tuple, boost::variant and boost::any. Again do not expect that usage of such solution will be easy to understand and straightforward for you.

这篇关于模板类的载体的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆