C++使模板类作为另一个类中的占位符

标签 c++ templates

我正在尝试创建一个模板类作为占位符类,它可以包含类似字符串和类型 T 对象。下面是我为此编写的代码。

#include <iostream>
#include <string>
#include <map>

using namespace std;

//A class which act as placeholder to hold
//unknown object. Something similar as Object
//in Java
template <typename T>
class Genric
{
    public:
        map<string, T> addP; //This will be placeholder for time
        // being.
};

class A
{
    public:
        Genric t1; //Have object of Genric class so that we can
        // access the member variable in future.
        void foo()
        {
            cout<<"Calling foo"<<endl;
        }
};

int main()
{
    A a1;
    a1.foo();
}

但是当我尝试编译时出现以下错误。

$ g++ tempClass.cxx
tempClass.cxx:21:9: error: invalid use of template-name 'Genric' without an argument list

上述 Genric 类的目的只是充当将来可以填充的成员变量之一的占位符类。 那么有没有一种方法可以编写这样的 Genric 类。

最佳答案

您正在将 Genric 定义为模板类,但随后尝试初始化 t1 而不为其提供类型。那就是你得到的错误。尝试例如:

Genric<int> t1;

或者,如果您正在寻找真正的运行时泛型,请查看 boost::any

关于C++使模板类作为另一个类中的占位符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15288827/

相关文章:

c++ - 如何使用模板参数对函数指针进行类型定义

c++ - 禁用 "desktop"子窗口的透明度

c++ - C++ 中的 gzip 压缩文件流

c++ - mutex::try_lock() 的意外行为

xslt - 调用同一个 xsl :template for different node names of the same complex type

loops - 包含循环的 Powershell 文本/html 模板

c++ - 通过 void* 向下转型/向上转型

c++ - QObject 通用信号处理程序

c++ - 用部分模板特化覆盖抽象成员函数

c++ - 我们不能从 initializer_list 创建一个 std::array,但是我们可以用一个带有可变参数的辅助函数来创建它吗?