如何正确使用模板?

时间:2017-05-17 01:26:57

标签: c++ templates clion

我正在尝试创建一个类似于这样的矢量类:

 template <typename T>
    class Vector
    {
     .
     .
     .
    };

    #include "vector.cpp"

然而,当我开始在&#34; vector.cpp&#34;中编写我的函数时,CLion抱怨我有重复的函数。我该如何解决这个问题?我相信NetBeans,我可以添加vector.h&amp; vector.cpp到一个名为&#34;重要文件&#34;的文件夹。这将解决问题。我不确定CLion中的等价物是什么。

1 个答案:

答案 0 :(得分:0)

template

的一般设计

<强> example.h文件

#ifndef EXAMPLE_H
#define EXAMPLE_H

// Needed includes if any

// Prototypes or Class Declarations if any

template<class T> // or template<typename T>
class Example {
private:
    T item_;

public:
    explicit Example( T item );
    ~Example();

    T getItem() const;
};

#include "Example.inl"

#endif // EXAMPLE_H

<强> Example.inl

// Class Constructors & Member Function implementations

template<class T>
Example<T>::Example( T item ) : item_(item) {
}

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

template<class T>
T Example<T>::getItem() const { 
    return item_;
}

<强> Example.cpp

#include "Example.h"

// Only need to have the include here unless if 
// the class is non template or stand alone functions
// are non-template type. Then they would go here.