0

Pretty new to working with templates in C++. I want to create a template specialization of a class function depending on whether a single object pointer is passed to the function, or a std::vector of object pointers. I want the std::vector to be passed by reference. I can't quite figure out the required syntax:

StateEvolver.h

#ifndef STATEEVOLVER_H
#define STATEEVOLVER_H

#include "Vehicle.hh"

class stateevolver
{
public:
    stateevolver();
    template<typename T> void evolveState(T, double time);
};

// Template specialization declarations for functions using either std::vector<vehicle*> or single vehicle pointer

template<>
void stateevolver::evolveState<std::vector<vehicle*>&>(std::vector<vehicle*> & , double time);

template<>
void stateevolver::evolveState<vehicle*>(vehicle*, double time);


#endif

StateEvolver.cpp

template<>
void stateevolver::evolveState<std::vector<vehicle*>&>(std::vector<vehicle*> & vehicleVec, double time) {
}

I instantiate this in another file like so:

MyStateEvolver.evolveState(vectorOfVehiclePointers, time); // COMPILE ERROR

and receive this compile time error:

undefined reference to `void stateevolver::evolveState<std::vector<vehicle*, std::allocator<vehicle*> > >(std::vector<vehicle*, std::allocator<vehicle*> >, double)'

Any ideas where I'm going wrong? Thanks.

kahamster
  • 51
  • 5
  • Possible duplicate of [Why can templates only be implemented in the header file?](https://stackoverflow.com/questions/495021/why-can-templates-only-be-implemented-in-the-header-file) – super Mar 20 '19 at 00:42
  • You specialized for `vector&`, but `T` is deduced as plain `vector`, without reference. So the compiler tries to call `evolveState`, which is not in fact implemented. Instead of template specialization, write two overloads - plain non-template functions. – Igor Tandetnik Mar 20 '19 at 01:32

0 Answers0