Gab*_*mas 2 c++ templates android-ndk
我正在使用Android NDK r6和Android SDK API 8(2.2).
我正在尝试使用模板实现像std :: vector这样的动态列表,但是我在编译的.o文件中遇到了很多错误.
一个样品:

正如您所看到的,错误是在已编译的.o文件中生成的,而不是在源文件中生成的.
班级定义:
template <class T>
class ArrayList{
private:
int mSize;
public:
/**
* Construye una lista dinámica vacía.
*/
ArrayList ();
/**
* Destructor.
*/
~ArrayList ();
/**
* Añade un elemento a la lista.
*
* @param element
* Elemento.
*/
void add (T element);
/**
* Obtiene un elemento de la lista.
*
* @param index
* Índice del elemento. Rango válido de valores: [0, size()]
* @return Elemento de la posición indicada o NULL si el índice no es válido.
*/
T get (int index);
/**
* Elimina un elemento de la lista.
*
* @param index
* Índice del elemento. Rango válido de valores: [0, size()]
*/
void remove (int index);
/**
* Vacía la lista.
*/
void clear ();
/**
* Consulta el número de elementos de la lista.
*
* @return Número de elementos.
*/
int size ();
/**
* Consulta si la lista esta vacía.
*
* @return true si está vaía, sinó false.
*/
bool isEmpty ();
};
Run Code Online (Sandbox Code Playgroud)
课程实施:
template <class T>
ArrayList<T>::ArrayList (){
mSize = 0;
}
template <class T>
ArrayList<T>::~ArrayList (){
}
template <class T>
void ArrayList<T>::add (T element){
}
template <class T>
T ArrayList<T>::get (int index){
T element;
return element;
}
template <class T>
void ArrayList<T>::remove (int index){
}
template <class T>
void ArrayList<T>::clear (){
}
template <class T>
int ArrayList<T>::size (){
return mSize;
}
template <class T>
bool ArrayList<T>::isEmpty (){
return true;
}
Run Code Online (Sandbox Code Playgroud)
课程用法:
ArrayList<OtherClass> list;
OtherClass foo;
list.add (foo);
Run Code Online (Sandbox Code Playgroud)
这是模板代码.您没有像普通C++类一样的cpp文件关系的头文件.我通常像这样重组它:
foo.h中:
#ifndef FOO_H
#define FOO_H
template <class T>
class Foo
{
Foo();
};
// Note that the header file INCLUDES the cpp file. This is simply to maintain
// the general .h .cpp file structure, but adapt it to template code, where the
// implementation is supposed to be in the header file and is not compiled.
#include "Foo.cpp"
#endif
Run Code Online (Sandbox Code Playgroud)
Foo.cpp中:
// Note that I do NOT include the header here. Also, do NOT compile this file.
// So if you have a makefile, be sure not to include this file in it.
template <class T>
Foo<T>::Foo()
{ }
Run Code Online (Sandbox Code Playgroud)
或者您可以将整个实现粘贴在头文件中,而根本没有cpp文件.这实际上更有意义,因为你不编译cpp文件.在这里阅读更多.