模板方法的未定义引用错误 [英] Undefined reference error for template method

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

问题描述

这已经驱使我疯了过去一个半小时。我知道这是一个小东西,但不能找到什么问题(事实上,这是一个下雨的星期五下午,当然不会帮助)。

This has been driving me mad for the past hour and a half. I know it's a small thing but cannot find what's wrong (the fact that it's a rainy Friday afternoon, of course, does not help).

我已经定义了以下类它将保存从文件读取的配置参数,并允许我从我的程序访问它们:

I have defined the following class that will hold configuration parameters read from a file and will let me access them from my program:

class VAConfig {
    friend std::ostream& operator<<( std::ostream& lhs, const VAConfig& rhs);

private:
    VAConfig();
    static std::string      configFilename;
    static VAConfig*        pConfigInstance;
    static TiXmlDocument*   pXmlDoc;
    std::map<std::string, std::string> valueHash;

public:
    static VAConfig* getInstance();
    static void setConfigFileName( std::string& filename ) { configFilename = filename; }
    virtual ~VAConfig();

    void readParameterSet( std::string parameterGroupName );
    template<typename T> T readParameter( const std::string parameterName );
    template<typename T> T convert( const std::string& value );
};

其中定义方法 convert() VAConfig.cpp 中作为

template <typename T>
T VAConfig::convert( const std::string& value )
{
    T t;
    std::istringstream iss( value, std::istringstream::in );
    iss >> t;
    return t;
}

很简单。但是当我从我的主程序使用

All quite simple. But when I test from my main program using

int y = parameters->convert<int>("5");

我得到一个未定义的引用'int VAConfig :: convert< int& ...'编译错误。 Ditto for readParameter()

I get an undefined reference to 'int VAConfig::convert<int>...' compilation error. Ditto for readParameter().

看了很多模板教程,但coul没有搞清楚。任何想法?

Looked at a lot of template tutorials but coul not figure this out. Any ideas?

推荐答案

模板代码实现不应该在 .cpp file:你的编译器必须在看到调用它们的代码的同时看到它们(除非你使用显式实例化以生成模板化对象代码,但即使 .cpp 是使用错误的文件类型)。

Templated code implementation should never be in a .cpp file: your compiler has to see them at the same time as it sees the code that calls them (unless you use explicit instantiation to generate the templated object code, but even then .cpp is the wrong file type to use).

你需要做的是将实现移动到头文件或者一个文件,如 VAConfig.t.hpp ,然后 #includeVAConfig.t.hpp每当您使用任何模板成员函数。

What you need to do is move the implementation to either the header file, or to a file such as VAConfig.t.hpp, and then #include "VAConfig.t.hpp" whenever you use any templated member functions.

这篇关于模板方法的未定义引用错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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