Template file not working correctly in CodeLite? - c++

Every time I create a new project in my workplace I run into the problem with templates. For example, I'll create a new class, which CodeLite will create a .h file and a .cpp file for me, and then I'll change that .cpp file into a .template by renaming the file. It sometimes works, and sometimes doesn't. Sometimes I have to clean my workplace for it to work, other times I need to exit out of CodeLite and reopen it. This time these solutions are not working for me, but maybe I am missing something. Here's my code:
.h file
#ifndef TABLE1_H
#define TABLE1_H
#include <cstdlib> // Provides size_t
namespace main_savitch_12A
{
template <class RecordType>
class table
{
public:
// MEMBER CONSTANT -- See Appendix E if this fails to compile.
static const std::size_t CAPACITY = 811;
// CONSTRUCTOR
table( );
// MODIFICATION MEMBER FUNCTIONS
void insert(const RecordType& entry);
void remove(int key);
// CONSTANT MEMBER FUNCTIONS
bool is_present(int key) const;
void find(int key, bool& found, RecordType& result) const;
std::size_t size( ) const { return used; }
private:
// MEMBER CONSTANTS -- These are used in the key field of special records.
static const int NEVER_USED = -1;
static const int PREVIOUSLY_USED = -2;
// MEMBER VARIABLES
RecordType data[CAPACITY];
std::size_t used;
// HELPER FUNCTIONS
std::size_t hash(int key) const;
std::size_t next_index(std::size_t index) const;
void find_index(int key, bool& found, std::size_t& index) const;
bool never_used(std::size_t index) const;
bool is_vacant(std::size_t index) const;
};
}
#include "table1.template" // Include the implementation.
#endif
.template file
template<class RecordType>
table<RecordType>::table(){
used = 32;
}
main file
#include <stdio.h>
#include "table1.h"
int main(int argc, char **argv)
{
printf("hello world\n");
return 0;
}
My template and my .h files are called table1. The error I am getting when I run the program is in the template file. It reads: "table does not name a type" How can I fix this issue?

In your template implementation your are missing the namespace, use this:
template <class RecordType>
main_savitch_12A::table<RecordType>::table()
{
used = 32;
};

Related

Compiling hybrid classes (templated and untemplated functions) into a static library

I'm writing a game engine lib, for the sake of science. I've written static libs successfully in the past, although there were no templated functions.
When dealing with templated functions, I use to sepparate their code from the untemplated ones. Templated functions code lie in the header file, while the others in the .cpp/.hpp file.
Below is a snippet of one of it's modules: signals.
// Connection.h
#pragma once
#include <memory>
#include <functional>
namespace mqs
{
using Disconnector = std::function<void(std::uint32_t)>;
class Connection final
{
public:
explicit Connection(std::shared_ptr<mqs::Disconnector> disconnector, std::uint32_t index);
bool connected() const;
void disconnect() const;
private:
std::uint32_t index;
std::weak_ptr<mqs::Disconnector> disconnector;
};
}
// Signal.h
#pragma once
#include <vector>
#include "connection.hpp"
namespace mqs
{
template <typename...>
class Signal;
template <typename R, typename... A>
class Signal<R(A...)> final
{
public:
Signal();
template <typename Lambda>
mqs::Connection connect(Lambda&& lambda) {
slots.push_back(std::forward<Lambda>(lambda));
return mqs::Connection(disconnector, slots.size() - 1U);
}
void operator()(A&&... args) const;
unsigned connections() const;
private:
std::vector<std::function<R(A...)>> slots;
std::shared_ptr<mqs::Disconnector> disconnector;
};
}
// Connection.hpp
#pragma once
#include "connection.h"
namespace mqs
{
Connection::Connection(std::shared_ptr<mqs::Disconnector> disconnector, std::uint32_t index) {
this->index = index;
this->disconnector = disconnector;
}
bool Connection::connected() const {
return !disconnector.expired();
}
void Connection::disconnect() const {
if (const auto& lock = disconnector.lock()) {
lock->operator()(index);
}
}
}
// Signal.hpp
#pragma once
#include "signal.h"
namespace mqs
{
template <typename R, typename... A>
Signal<R(A...)>::Signal() {
disconnector = std::make_shared<mqs::Disconnector>([this](std::uint32_t index) {
slots.erase(slots.begin() + index);
});
}
template <typename R, typename... A>
void Signal<R(A...)>::operator()(A&&... args) const {
for (auto& slot : slots) {
slot(std::forward<A>(args)...);
}
}
template <typename R, typename... A>
unsigned Signal<R(A...)>::connections() const {
return slots.size();
}
}
It compiles and all, however one of the problems I've been dealing with, is that mqs::Signal (signal.hpp) cannot be included in different headers or it will cause a function already has a body. When including signal.h I get unresolved external symbol which makes sense.
I've also tried making inline all the functions defined in their .hpp files above.
Is there any way to achieve this other than using huge header-only approaches?
As you already figured out, you need to make the function templates inline. This is necessary because the templates first need to be instantiated to become compilable functions, and that means the compiler needs source code.
However, if you look at members like Signal<R(A...)>::disconnector;, you'll notice that they are not dependent on R or A.... Hence, you could move them to a non-template base class.
There's a fairly common convention to use the extension .ipp for implementation files that still need to be included, e.g. because they contain template code. These will typically be included by the corresponding .hpp file, just before the #endif of the header guard. Therefore an .ipp file doesn't need its own header guard.

C++ redefinition error, Why am I getting this error?

I had a redefinition problem but I noticed that I already included .cpp file in the .hpp file so my mistake was including the .hpp file in my .cpp file again
Now I am getting this error, something to do with templates.
Also while you fix my problem, can you explain to me what template class does?
cplusplus.com is not that descriptive.
Thank you. :)
//implementation
template<class T>
ArrayBag<T>::ArrayBag() : item_count_(0){}
-------------WARNING YOU ARE NOW LEAVING IMPLEMENTATION---------------------------
//interface
#ifndef ARRAY_BAG_H
#define ARRAY_BAG_H
#include <vector>
template<class T>
class ArrayBag
{
protected:
static const int DEFAULT_CAPACITY = 200;
T items_[DEFAULT_CAPACITY];
int item_count_;
int get_index_of_(const T& target) const;
public:
ArrayBag();
int getCurrentSize() const;
bool isEmpty() const;
//adds a new element to the end, returns true if it was successfully been added
bool add(const T& new_entry);
bool remove(const T& an_entry);
void clear();
bool contains(const T& an_entry) const;
int getFrequencyOf(const T& an_entry) const;
std::vector<T> toVector() const;
void display() const;
//overloading operators for objects
void operator+=(const ArrayBag<T>& a_bag);
void operator-=(const ArrayBag<T>& a_bag);
void operator/=(const ArrayBag<T>& a_bag);
};
#include "ArrayBag.cpp"
#endif
-------------WARNING YOU ARE NOW LEAVING INTERFACE---------------------------
//error
5 C:\Users\minahnoona\Desktop\ArrayBag.cpp expected constructor, destructor, or type conversion before '<' token
5 C:\Users\minahnoona\Desktop\ArrayBag.cpp expected `;' before '<' token
Don't call your ArrayBag.cpp a .cpp file. Template implementations go in header files, and the name should reflect that.
If you want the implementation in a separate file (you don't strictly need to), call it ipp or tpp. Something the project system won't try to compile on its own.
Then include it from the .hpp and don't include the .hpp from the .ipp.

C++: error: ‘Vector’ does not name a type

I am writing two templated classes (for academic reasons):
'class Vector', which mimics a C++ vector using a dynamic array.
'class Set', which creates a set using a vector object.
Vector.cpp -
#ifndef __CS_VECTOR_H_
#define __CS_VECTOR_H_
#include <cstdlib>
#include "Set.cpp"
template <class Type>
class Vector
{
public:
Vector(unsigned int capacity = DEFAULT_CAPACITY);
Vector(const Vector<Type>& rhs);
~Vector();
unsigned int capacity() const;
unsigned int size() const;
bool empty() const;
void push_back(const Type& data);
bool remove(const Type& data);
void clear();
bool at(unsigned int pos, Type& data) const;
int get_array_size() const;
Type& operator[](unsigned int pos) const;
Vector& operator=(const Vector& rhs);
private:
static const unsigned int DEFAULT_CAPACITY = 3;
void generate_larger_array(unsigned int capacity);
int array_size_ = 0;
int array_capacity_;
Type *array_;
};
//Function definitions here.
//#include "Set.cpp"
#endif
Set.cpp -
#ifndef __CS_SET_H_
#define __CS_SET_H_
#include "Vector.cpp"
template <class Comparable>
class Set
{
public:
unsigned int size() const;
bool empty() const;
bool contains(const Comparable& data) const;
bool insert(const Comparable& data);
bool remove(const Comparable& data);
void clear();
int get_size();
private:
int element_;
Vector<Comparable> set_;
};
//Function definitions here
//#include "Vector.cpp"
#endif
Main.cpp
#include "Set.cpp"
#include "Vector.cpp"
When I compile my code, I receive an error telling me:
error: ‘Vector’ does not name a type Vector<Comparable> set_;
When declaring my set_ object in Set.
These are both cpp files that are included into a file main.cpp. The set cpp file does contain the #include vector.cpp and vice versa
main.cpp just has code that tests the class functionality. I receive this error when attempting to compile either the main.cpp file. The main.cpp file is written by my instructor, so I am not entirely sure I should post it here.

Error in C++ : redefinition of class constructor using templates

Anybody know how I can fix these errors?
i have been looking at it for a while and just cannot figure out what to do.
Error:
indexList.cpp:18: error: redefinition of `indexList<T>::indexList()'
indexList.cpp:18: error: `indexList<T>::indexList()' previously declared here
indexList.cpp:30: error: redefinition of `bool indexList<T>::append(T)'
indexList.cpp:30: error: `bool indexList<T>::append(T)' previously declared here
cpp file:
//
//
//
//
//
//
#include "indexList.h"
#include <iostream>
using namespace std;
//constuctor
//Descriptions: Initializes numberOfElement to 0
// Initializes maxSize to 100
//Parameters: none
//Return: none
template <class T>
indexList<T>::indexList()
{
numberOfElements = 0;
maxSize = 100;
}
//Name: append
//Purpose: Adds element to the end of the list. If array is full, returns false
//Paramters: value - thing to append
//Return: true if append succeeds, false otherwise
template <class T>
bool indexList<T>::append(T value)
{
if (maxSize > numberOfElements)
{
list[numberOfElements] = value;
numberOfElements ++;
return true;
}
else
return false;
}
I didn't put all the the cpp file because the rest of the errors are similar to the ones above, and it is quite long
header:
#include <iostream>
using namespace std;
#ifndef INDEXLIST_H
#define INDEXLIST_H
template <class T>
class indexList
{
public:
indexList();
bool append(T value);
bool insert(int indx, T value);
bool replace(int indx, T newValue);
bool retrieve(int indx, T &value) const;
bool remove(int indx);
void sort();
int search(T value) const;
private:
T list[100];
int numberOfElements;
int maxSize;
};
template <class T>
ostream &operator<<(ostream &outStream, const indexList<T> &lst);
#include "indexList.cpp"
#endif
I did put the entire header
Each of your two files tries to include the other, which can cause the preprocessor to output some repeated code.
Take the #include "indexList.h" out of the file indexList.cpp.
Also, your build process should not attempt to compile indexList.cpp into an object file.
Another way to arrange things would be to just put all the contents you currently have in indexList.cpp near the end of indexList.h, and there would be no indexList.cpp file at all.
What you've done is ok, but you must realise that the .cpp file should not itself be compiled into an object - instead, just include the .h file from your application code:
// main.cc
#include "indexList.h"
int main()
{
indexList<int> il;
}
c++ -o main main.cc
I'd bet it's because you've tried to do a c++ -c indexList.cpp or c++ indexList.cpp that you get the errors (or perhaps your make tool is trying that automatically for all .cpp files in your source code directories - you could try renaming indexList.cpp to indexList.inl or .inc or whatever - remember to change the name in indexList.h too - to see if that fixes the problem), as in that situation the definitions are seen twice: once as the compile includes indexList.h, and again as it finishes compiling indexList.cpp.
There's no need to include indexList.h from within the .cpp anyway - that makes it look as if the indexList.cpp is designed for separate compilation.
Put any of your templated methods in an indexList.inl file, and include that from your header. Don't include the header from this file.
Put any other methods in your indexList.cpp file. Include the header from this file.

failing to invoke template class, c++

I've defined a template class like so (providing .hpp file):
#ifndef PERSOANLVEC_H_
#define PERSOANLVEC_H_
#include <vector>
using namespace std;
template<class T, class PrnT> class PersoanlVec {
public:
PersoanlVec();
~PersoanlVec();
void push_back(T t);
void erase(int index);
PersoanlVec& operator[](int index);
const PersoanlVec& operator[](int index) const;
void print() const;
size_t size();
private:
vector<T> _vector;
};
#endif /* PERSOANLVEC_H_ */
Now, everything compiles ok with this class. When I try to use it I get
undefined reference to PersoanlVec<Person, Person>::PersoanlVec()'.
Here's where I call it:
#include "Person.h"
#include "PersoanlVec.hpp"
#include <cstdlib>
int main(void)
{
Person p1("yotam");
Person p2("yaara");
PersoanlVec<Person,Person> *a = new PersoanlVec<Person,Person>(); //<---ERROR HERE
return EXIT_SUCCESS;
}
This is my first try with templates, its not very clear for me obviously. I DO have a constructor with no parameters, Any ideas?
Thanks!
Do you have the content of your constructor and functions in a .cpp file? If yes, there's your problem. Put them in the header file, possible just inline in the class itself:
template<class T, class PrnT> class PersoanlVec {
public:
PersoanlVec(){
// code here...
}
~PersoanlVec(){
// code here...
}
void push_back(T t){
// code here...
}
void erase(int index){
// code here...
}
PersoanlVec& operator[](int index){
// code here...
}
const PersoanlVec& operator[](int index) const{
// code here...
}
void print() const{
// code here...
}
size_t size(){
// code here...
}
private:
vector<T> _vector;
};
For the reason, have a look here.
I am pretty sure you just forgot to add the file to the compilation process. Be careful with your misspelling, since that can cause generic pain.
Whenever you have different compilation units (classes for example, each with their .h/.cpp), your classes need to know of the interfaces, reason for which you normally include the header files, yet the compiler also needs to know the implementations so that it can bind together your binary file.
As such, you will need to call the compiler passing all the .cpp files in your project to it, otherwise it will fail letting you know you are referencing unimplemented pieces.
You need to have all of your template function definitions held in the header file rather than the CPP file - this is basically because the template definition will be used multiple times to create multiple types depending on what parameters you pass in to it as type parameters around your code. The only template related functions that should ever be defined in the CPP file are template specialization functions - those where you want to explicitly say (if user passed in type A and B then do this specifically instead of the default action).