What I'm aiming for, Is that I would like a function template to convert a vector to a type* array for ease of use. Instead of creating multiple functions for the "same" functionality.
With following code(Note function is inside namespace Khan):
// Func.h
template <typename T>
T* vector_to_array(std::vector<T> vec);
// Func.cpp
template <typename T>
T* vector_to_array(std::vector<T> vec)
{
T* arr = new T[vec.size()];
std::copy(vec.begin(), vec.end(), arr);
return arr;
}
// Inside main function
std::vector<int> test_vec = { 0, 2, 3 };
int* test_arr = Khan::vector_to_array(test_vec);
I get the following error:
undefined reference to Khan::vector_to_pointer(std::vector<int, std::allocator<int> >)
I tested different ways, and made a specific function for an int as in the example above excluding the template.
Thus my question is, what is the plausible cause of these errors, and what would be a possible fix?
And to clarify my goal. What my goal is for this, is for the function not dependent on the type, to return a copy of a vector in a C-styled array.
*Edit: Rewrote with complete code, and parts of error was missing.
Solved: As this question is a duplicate, I found my answers in the other post. To summarise what caused this issue, the previous stated error was the cause of declaring the template in a ".cpp" file. And was fixed with declaring and defining the template inside the header file.