繁体   English   中英

如何正确使用模板?

[英]How to properly use Templates?

我正在尝试创建一个看起来像这样的向量类:

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

    #include "vector.cpp"

但是,当我开始在“ vector.cpp”中编写函数时,CLion抱怨我有重复的函数。 我该如何解决? 我相信在NetBeans中,我可以将vector.h和vector.cpp添加到名为“重要文件”的文件夹中,这将解决问题。 我不确定CLion中的等效功能是什么。

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.

暂无
暂无

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

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