I am new to C++ templates and I want to write a template function which, depending on its parameters, returns either a single object or a vector of objects.
I have a configuration class that holds key/value pairs. Say I have the key "parent.child.1", it should return a single object with id=1. If I have the key "parent.child" then it should return all the objects under child. All the objects under child are same type but different childs may hold different objects.
In my mind the resulting code would look like this:
getParameter<MyObject>(key, value); //value is a referance, if key found copy it into value
getParameter<std::vector<MyObject>>(key, vectorValue); //value is a referance to the vector
I can do this by specializing the getParameter function for each type, times two, but I think I can reduce the boilerplate code a lot for each different type if I do use templates.
I have followed this other SO question and used it in my code like this(I am using c++11 so its a bit different):
template<typename T>
void getParameter(const string& key, typename enable_if< !is_vector<T>::value,T>::type& val) {...} //Works fine when calling getParameter<MyObject>(key, value);
template<template<typename...>> class C, typename U>
void getParameter(const string& key, typename enable_if< is_vector<C<U>>::value, C<U>>::type& val) {...}//Fails in compile
It fails substituting both of the functions when I call getParameter<std::vector<MyObject>>(key, vectorValue);. Why is that?