0

I want to write my own object parser. It doesn't matter what is the object, suppose it is a JSON-like object, PyObject, smth serializable or similar. I want to implement parser as separate library. Since object can contains different types of values I want to use templates like follows (thanks for @MarekR for this solution):

// parser.h

...    
struct ComplexObject {
  // any object like JSON or serializable
};

void get_from_object(ComplexObject* obj, uint32_t& value);
void get_from_object(ComplexObject* obj, double& value);
void get_from_object(ComplexObject* obj, std::string& value);

template <typename ValueType>
void get_from_object(ComplexObject* obj, std::vector<ValueType>& value);

template<typename ValueType>
ValueType from_object(ComplexObject* obj) {
  ValueType value;
  get_from_object(obj, value);
  return value;
}

// parser.cpp #include "parser.h" ...

void get_from_object(ComplexObject* /*obj*/, uint32_t& /*value*/) {
  std::cout << "get_from_object for uint32_t" << std::endl;
}

void get_from_object(ComplexObject* /*obj*/, double& /*value*/) {
  std::cout << "get_from_object for double" << std::endl;
}

void get_from_object(ComplexObject* /*obj*/, std::string& /*value*/) {
  std::cout << "get_from_object for string" << std::endl;
}

template <typename ValueType>
void get_from_object(ComplexObject* obj, std::vector<ValueType>& /*value*/) {
  std::cout << "get_from_object for vector" << std::endl;
  // some manipulating with obj
  ValueType elem;
  get_from_object(obj, elem);
}

From these 2 files I build the library. After that in main.cpp i write:

#include "parser.h"

int main() {
  ComplexObject A;

//  from_py_object<std::string>(&A);  <-- it works
//  from_py_object<double>(&A);  <-- it also works
//  from_py_object<uint32_t>(&A);  <-- it works too
//  from_py_object<std::vector<std::string>>(&A); <-- it gets me unresolved reference error

  return 0;
}

But if I build main.cpp together with parser.cpp in one binary all errors disappears.

In general I understand why i receive such errors. It is because there are no template specializations. But I don't understand how to fix this.

borune
  • 490
  • 3
  • 20

0 Answers0