c++ ubuntu linux .cpp 中的模板
我目前在 Ubuntu9.10 - c++ 中工作。 我需要在方法中定义一个通用对象。我必须在 .h 文件中定义该方法。我该怎么做呢?我执行了以下操作:
file.h
class ana
{
//code
public:
template <class T> bool method (T &Data);
};
file.cpp
//code
template <class T>
bool ana::method(T &Data)
{
//code
}
我创建了 .a
文件。
在 test.cpp
中:
//code
main()
{
//code
Ana* ann = new Ana();
if (ann->method(*ann)){//code}
}
使用 g++ test.cpp -o test libfile.a
编译后出现错误:对 bool.... 的未定义引用
代码> 为什么?还有另一种方法来创建通用对象吗?
I am currently working in Ubuntu9.10 - c++.
I need to define an generic object in a method. I have to define the method in .h file. How can I do it? I did the following:
file.h
class ana
{
//code
public:
template <class T> bool method (T &Data);
};
file.cpp
//code
template <class T>
bool ana::method(T &Data)
{
//code
}
I've created the .a
file.
In test.cpp
:
//code
main()
{
//code
Ana* ann = new Ana();
if (ann->method(*ann)){//code}
}
After compiling with g++ test.cpp -o test libfile.a
I have the error: undefined reference to bool....
Why? Is there another way to create a generic object?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
通常的问题。看一下: http://www.parashift.com/c++ -faq-lite/templates.html#faq-35.13。
只需将所有内容放入头文件中即可。
file.hpp
将其包含在您的 main.cpp 中,它应该可以正常工作。
The usual problem. Have a look: http://www.parashift.com/c++-faq-lite/templates.html#faq-35.13.
Just put everything into a header file.
file.hpp
Include this in your main.cpp and it should work fine.
将函数定义与声明放在一起(在头文件本身中)绝对有帮助,并且是选择的方式。但是,如果您想要分隔函数定义,请在
.cpp
文件末尾添加以下行。它称为显式实例化。这将处理链接器错误。我尝试了一些代码,根据您给出的内容,这似乎有效:file.h:
file.cpp:
使用此方法的缺点之一是对于您希望此函数支持的每种数据类型,都必须包含这些行。因此,现在该方法函数将仅针对
int
和double
运行。代码的规范应该是这样的,即永远不会为上述以外的数据类型调用该方法。HTH,
斯里拉姆
Putting function definitions together with declarations (in the header files itself) definitely helps and is the way of choice. But, in case you want to separate the function definitions, have the following lines at the end of the
.cpp
file. Its calledexplicit instantiation
.This will take care of linker errors. I tried some code, and this seems to work, based on what you have given:file.h:
file.cpp:
One of the downsides of using this method is that these lines will have to be included for every data type that you want this function to support. So, now the method function will run ONLY for
int
anddouble
. The specs for your code should be such that method is never called for data types other than the above.HTH,
Sriram
file.cpp
构建到二进制文件中。file.cpp
into the binary.您需要更改头文件中
method()
方法的定义:查看以下链接以获取详细说明 - http://www.parashift.com/c++-faq-lite/templates.html#faq-35.12
You need to change the definition of your
method()
method to be in the header file:Check the following link out for a detailed explanation - http://www.parashift.com/c++-faq-lite/templates.html#faq-35.12
只需在 main.cpp 中包含 cpp 文件,如下所示:#include "ana.cpp" 并且不会出现错误。
Just include cpp file in main.cpp like this: #include "ana.cpp" and you will not have errors.