在成员变量中保存任何类型的C ++模板类 [英] Hold any kind of C++ template class in member variable

查看:132
本文介绍了在成员变量中保存任何类型的C ++模板类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个类。

第一个类(A)是用模板构建的。

The first class (A) is builded with an template.

template <class T>
class A
{
    public:
        T value;
};

第二个类(B)应该有一个A类的对象作为成员变量。像这样:

The second class (B) should have an object of class A as member variable. Like this:

class B
{
    public:
        A<int> value;
};

但现在我想在类中使用任何 A.不仅 int
显然我不能声明一个(member-)变量,它包含任何类型的类。
所以,我需要这样的东西:

But now i want to use any kind of template-class in class A. Not only int. Apparent I can't declare a (member-)variable which contains any kind of a class. So, I need something like this:

class B
{
    public:
        A<*> value;
};

这个问题有没有(干净)解决方案?

Is there any (clean) solution for this problem?

- 来自德国,巴斯蒂安的问候语

-- Greeting from Germany, Bastian

推荐答案

您不能有一个类 B因为 B 必须是定义良好的类,并且 A / code>是不同类型 T 不同类型。您可以使 B 模板本身:

You cannot have a single class B with "any" member object, because B has to be a well-defined class, and A<T> is a different type for different types T. You can either make B a template itself:

template <typename T>
class B
{
  A<T> value;
};

或者您可以查看 boost :: any ,这是任意类型的类型擦除容器(但是使用它需要一定量的额外工作)。 任何类仅适用于 value 类型,但它不是完全任意的。

or you can take a look at boost::any, which is type-erasing container for arbitrary types (but making use of it requires a certain amount of extra work). The any class only works for value types, though, it's not completely arbitrary.

这篇关于在成员变量中保存任何类型的C ++模板类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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