简体   繁体   English

如何正确使用模板?

[英]How to properly use Templates?

I am trying to create a vector class that looks something like this: 我正在尝试创建一个看起来像这样的向量类:

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

    #include "vector.cpp"

However, when I start writing my functions in "vector.cpp", CLion complains that I have duplicate functions. 但是,当我开始在“ vector.cpp”中编写函数时,CLion抱怨我有重复的函数。 How do I work around this? 我该如何解决? I believe in NetBeans, I can add vector.h & vector.cpp to a folder called "Important Files" which would fix the problem. 我相信在NetBeans中,我可以将vector.h和vector.cpp添加到名为“重要文件”的文件夹中,这将解决问题。 I am not sure what the equivalent in CLion is. 我不确定CLion中的等效功能是什么。

General Design of a template template一般设计

example.h 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 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 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.

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM