0

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. 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. I am not sure what the equivalent in CLion is.

Newtron Labs
  • 809
  • 1
  • 5
  • 17
darylnak
  • 39
  • 1
  • 6
  • 2
    don't include cpp files or you gonna have a bad time – Guillaume Racicot May 17 '17 at 01:31
  • 1
    in the meantime, take a look at this question: http://stackoverflow.com/questions/495021/why-can-templates-only-be-implemented-in-the-header-file – Guillaume Racicot May 17 '17 at 01:32
  • @GuillaumeRacicot It's perfectly fine to include the .cpp for template source files. The point is to ensure that the declarationsand definitions are in the same compilation unit. What are the contemts of your .cpp file, and what are your compilation commands? You shouldn't specify the .cpp in your list of source files and the .cpp shouldn't #include the .hpp. – synchronizer May 17 '17 at 01:35
  • 3
    @synchronizer I'd highly recommend using an alternative file extension, such as inl. There are tools that blindly treat each cpp files the same. Since that particular cpp will be included by many file, it's a header, by definition. Using .cpp for a header is highly misleading. – Guillaume Racicot May 17 '17 at 01:41
  • And not insignificant is constantly having to explain to people why you included a cpp file and why it was a good idea. – user4581301 May 17 '17 at 01:51
  • @GuillaumeRacicot Fair enough. I used .tpp for template for a while but IDEs and text editors recognize only .cpp, .cc, .h, and .hpp. There are trade-offs. – synchronizer May 18 '17 at 00:40

1 Answers1

0

General Design of a 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.
Francis Cugler
  • 7,788
  • 2
  • 28
  • 59