开发者

Undefined reference to constructor, generic class

I'm just learning template programming in C++ and have a problem with linker unable to find my class'es cons开发者_StackOverflow社区tructor's definition. What can be the cause? Code below.

Logger.h

template <class T>
class Logger {
public:
    Logger(NodeHandle& nh, char* topic, short pubFrequency);
    virtual ~Logger();

    void publish();
    T& getMsg();

private:
    NodeHandle& nh_;
    Publisher publisher_;
    T msg_;
    const char* topic_;
    const short pubFrequency_;
};

Logger.cpp

template <class T>
Logger<T>::Logger(NodeHandle& nh, char* topic, short pubFrequency) :
    nh_(nh),
    topic_(topic),
    pubFrequency_(pubFrequency),
    publisher_(topic_, static_cast<Msg*>(&msg_)) {}

template <class T>
Logger<T>::~Logger() {}

Then, when I'm trying to create a Logger instance in main.cpp

NodeHandle nh; 
Logger<std_msgs::String> logger(nh, "test", 10);

the linker is complaining:

undefined reference to `Logger<std_msgs::String>::Logger(NodeHandle&, char*, short)'

What am I doing wrong? There are no compiler errors, so all includes are there, I guess.


You need the templated implementation to be in the header.

Any code referencing the templated code needs to "see" the implementation so the compiler can generate the code from the template.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜