对构造函数、泛型类的未定义引用
我刚刚学习 C++ 模板编程,并且遇到链接器无法找到我的类构造函数定义的问题。可能是什么原因?代码如下。
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() {}
然后,当我尝试在 main.cpp 中创建 Logger 实例时,
NodeHandle nh;
Logger<std_msgs::String> logger(nh, "test", 10);
链接器会抱怨:
undefined reference to `Logger<std_msgs::String>::Logger(NodeHandle&, char*, short)'
我做错了什么?没有编译器错误,所以我猜所有包含的内容都在那里。
I'm just learning template programming in C++ and have a problem with linker unable to find my class'es constructor'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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您需要将模板化实现放在标头中。
任何引用模板化代码的代码都需要“查看”实现,以便编译器可以从模板生成代码。
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.