ubuntu linux .cpp中的c ++模板 [英] c++ templates in ubuntu linux .cpp

查看:106
本文介绍了ubuntu linux .cpp中的c ++模板的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前工作在Ubuntu9.10 - c ++。
我需要在方法中定义一个通用对象。我必须在.h文件中定义方法。我该怎么办呢?我执行了以下操作:

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

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 文件。

code> test.cpp :

In test.cpp:

//code
main()
{
    //code
    Ana* ann = new Ana();

    if (ann->method(*ann)){//code}
}

使用 g ++ test.cpp -o test libfile.a编译之后,我有错误:未定义的bool引用.... 为什么?是否有另一种方法来创建一个通用对象?

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?

推荐答案

将函数定义与声明并且是选择的方式。但是,如果要分离函数定义,请在 .cpp 文件的末尾添加以下行。它调用显式实例化。这将处理链接器错误。我尝试了一些代码,这似乎工作,基于你给了:

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 called explicit 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:

#ifndef __ANA_H__
#define __ANA_H__

template <class T>
class ana {

  public: 
    bool method(T& data);
};

#endif

file.cpp:

#include <ana.h>
#include <iostream>
using namespace std;

template <typename T>
bool ana<T>::method(T& data) {
  cout << "Data = " << data << endl;
  if(data > 0) {
    return true;
  }
  return false;
}

//explicit instantiation for avoidance of g++ linker errors.
template
bool ana<int>::method(int& data);

template
bool ana<double>::method(double& data)

使用此方法的缺点之一是,您希望此函数支持的每个数据类型都必须包含这些行。所以,现在的方法函数将只对 int double 运行。你的代码的规格应该是这样的方法从来不调用上述以外的数据类型。
HTH,

Sriram

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 and double. The specs for your code should be such that method is never called for data types other than the above. HTH,
Sriram

这篇关于ubuntu linux .cpp中的c ++模板的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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