我如何使用模板类方法? C ++ [英] How do I use template class methods? C++

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

问题描述

我想创建一个存储未定义数量的任何类型变量(或实际指针)的类。



我尝试过:



I want to create a class that stores undefined number of variables of any type (or their pointers actually).

What I have tried:

// ThEz.hpp
using namespace std;

class ThEz
{
    private:
        map <string, void*> mx_;
    public:
        void add( string name, void * ag );
        template <typename T> T get( string name );
};

// ThEz.cpp
// set method looks alright
template <typename T> T ThEz::get( string name ) {
    T * rv = (T*) mx_[name];
    return *rv;
}

// main.cpp
int x = 50;
    ThEz th1;
    th1.add( "hello", &x );

    int y = th1.get<int>("hello"); //error here

    cout << y;





编译器(GNU GCC)说:

undefined对`int ThEz :: get<的引用int>(std :: string)'



Compiler (GNU GCC) says:
undefined reference to `int ThEz::get<int>(std::string)'

推荐答案

实际上你的代码用 g ++编译(我正在使用版本 5.2.1 )。它为 th1.add 调用提供了未定义的引用,但这是正确的,因为你从未定义它。
Actually your code compiles with g++ (I am using version 5.2.1). It gives 'undefined reference' for the th1.add call, but that's correct, since you never defined it.


这篇关于我如何使用模板类方法? C ++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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