How to write a template, convert a vector to Json :: Value (jsoncpp)

I wrote a template (as shown below), but it cannot compile

template<class t, template<typename> class iterable> Json::Value iterable2json(const iterable<t>& cont) { Json::Value v; for(const t& elt : cont) { v.append(elt); } return v; } std::vector<int> vec{1,2,3}; Json::Value v = iterable2json(vec) 

error C3312: the called function "begin" was not found for the type "const std :: _ Vector_val <_Val_types> '

with [_Val_types = std :: _ Simple_types]

see the link to the instance of the function template "Json :: Value iterable2json, std :: _ Vector_val> (const std :: _ Vector_val <_Val_types> &) '

with [_Value_type = int, _Val_types = std :: _ Simple_types]

error C3312: the function 'end' was not found for the called type 'const std :: _ Vector_val <_Val_types>'

with [_Val_types = std :: _ Simple_types]

error C2065: 'elt': undeclared identifier

+4
c ++ templates
Nov 06 '14 at 6:26
source share
1 answer

The problem is that the compiler cannot infer the type t , since it is indirectly determined using the template template parameter. However, in fact, there is no need to do something like this in the first place! The following works fine:

 template <typename Iterable> Json::Value iterable2json(Iterable const& cont) { Json::Value v; for (auto&& element: cont) { v.append(element); } return v; } 

(well, since I don't have the Json library that you use, I have not tried to compile it, but I think everything should be fine).

+5
Nov 06
source share



All Articles