I'm trying to make a quick utility class that extends std::vector
through composition. For this, I want to make it as generic as possible.
The class works well when declared and implemented in a single file (i.e. main.cpp):
main.cpp
#include <iostream>
#include <algorithm>
#include <vector>
template<typename T>
class FVector {
public:
FVector(std::vector<T> vector): _vector(vector) {}
template <typename unaryOperation>
void forEach(unaryOperation op) {
std::for_each(_vector.begin(),_vector.end(),op);
};
private:
std::vector<T> _vector;
};
int main(int argc, const char * argv[]) {
auto printInt = [](int i){ std::cout << i << std::endl; };
std::vector<int> numbers{1, 2, 3, 4, 5};
FVector<int> fNumbers{numbers};
fNumbers.forEach(printInt);
return 0;
}
But when I try to put the class in its own .h and .cpp file, the compiler won't find the Constructor nor the function.
FVector.h
...
#include <vector>
template<typename T>
class FVector {
public:
FVector( std::vector<T> );
template <typename unaryOperation>
void forEach(unaryOperation);
private:
std::vector<T> _vector;
};
...
FVector.cpp
#include "FVector.hpp"
#include <algorithm>
template <typename T>
FVector<T>::FVector( std::vector<T> vector ): _vector(vector) {}
template <typename T>
template <typename unaryOperation>
void FVector<T>::forEach(unaryOperation op) {
std::for_each(_vector.begin(),_vector.end(),op);
}
main.cpp
#include <iostream>
#include "FVector.hpp"
int main(int argc, const char * argv[]) {
auto printInt = [](int i){ std::cout << i << std::endl; };
std::vector<int> numbers{1, 2, 3, 4, 5};
FVector<int> fNumbers{numbers};
fNumbers.forEach(printInt);
return 0;
}
error
Function 'FVector::forEach<(lambda at blah/main.cpp:95:21)>' has internal linkage but is not defined
Clearly something in my syntax is very wrong, but I can't find how to declare/implement the functions.
Thanks!