如何编写一个模板将向量转换为Json :: Value(jsoncpp) [英] how to write a template converts vector to Json::Value (jsoncpp)

查看:995
本文介绍了如何编写一个模板将向量转换为Json :: Value(jsoncpp)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我写了一个模板(如下),但它无法编译

i wrote a template(like below) but it fails to 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)

错误C3312:no callable'begin 'function for type'const std :: _ Vector_val< _Val_types>'

error C3312: no callable 'begin' function found for type 'const std::_Vector_val<_Val_types>'

与[_Val_types = std :: _ Simple_types]

with[ _Val_types=std::_Simple_types ]

参见函数模板实例化'Json :: Value iterable2json,std :: _ Vector_val>(const std :: _ Vector_val <_Val_types>&)'

see reference to function template instantiation 'Json::Value iterable2json,std::_Vector_val>(const std::_Vector_val<_Val_types> &)' being compiled

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

with[ _Value_type=int, _Val_types=std::_Simple_types ]

错误C3312:没有可调用的'end'函数找到类型'const std :: _ Vector_val< _Val_types >'

error C3312: no callable 'end' function found for type 'const std::_Vector_val<_Val_types>'

与[_Val_types = std :: _ Simple_types]

with[ _Val_types=std::_Simple_types ]

错误C2065:'elt':undeclared identifier

error C2065: 'elt' : undeclared identifier

推荐答案

问题是编译器无法推导类型 t 因为它是通过模板模板参数间接确定的。然而,实际上没有必要做这样的事情在第一!以下工作很好:

The problem is that compiler can't deduce the type t as it is indirectly determined through the template template parameter. However, there is actually no need to do anything like that in the first place! The following works just fine:

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

(好吧,因为我没有 Json 你使用的库我没有尝试编译它,但我认为应该很好)。

(well, since I don't have the Json library you are using I havn't tried to compile it but I'd think it should be fine).

这篇关于如何编写一个模板将向量转换为Json :: Value(jsoncpp)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆