Why can't I pass std::vector<MyType> to this function with template template parameters?

Viewed 63

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?

1 Answers

The 2nd getParameter takes two template parameters, but getParameter<std::vector<MyObject>>(...) specifies only one template argument then it won't be selected.

I think just making the 2nd getParameter taking one template parameter should be fine. e.g.

template<template T>
void getParameter(const string& key, typename enable_if< is_vector<T>::value, T>::type& val) {...}

If you want to get the element type you can use the member type value_type of std::vector like typename T::value_type.

Related