Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/templates/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 如何正确使用模板?_C++_Templates_Clion - Fatal编程技术网

C++ 如何正确使用模板?

C++ 如何正确使用模板?,c++,templates,clion,C++,Templates,Clion,我正在尝试创建一个向量类,看起来像这样: template <typename T> class Vector { . . . }; #include "vector.cpp" 模板 类向量 { . . . }; #包括“vector.cpp” 然而,当我开始在“vector.cpp”中编写函数时,CLion抱怨我有重复的函数。我如何解决这个问题?我相信NetBeans,我可以将vector.h&vector.cp

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

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

    #include "vector.cpp"
模板
类向量
{
.
.
.
};
#包括“vector.cpp”

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

模板的一般设计

示例.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

不要包含cpp文件,否则你会有一段不愉快的时光,看看这个问题:@GuillaumeRacicot将.cpp包含在模板源文件中是非常好的。关键是要确保声明和定义位于同一个编译单元中。.cpp文件的内容是什么?编译命令是什么?您不应该在源文件列表中指定.cpp,.cpp不应该包含.hpp。@我强烈建议使用其他文件扩展名,如inl。有些工具盲目地将每个cpp文件视为相同的文件。由于该特定的cpp将包含在许多文件中,因此根据定义,它是一个头文件。使用.cpp作为标题是非常容易误导的。而且,不断地向人们解释为什么要包含一个cpp文件以及为什么它是一个好主意也并非无关紧要。
// 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_;
}
#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.