如何编写模板将矢量转换为Json :: Value(jsoncpp)

try*_*000 4 c++ templates

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

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)
Run Code Online (Sandbox Code Playgroud)

错误C3312:找不到类型为'const std :: _ Vector_val <_Val_types>'的可调用'begin'函数

[_Val_types = std :: _ Simple_types]

请参阅函数模板实例化'Json :: Value iterable2json,std :: _ Vector_val>(const std :: _ Vector_val <_Val_types>&)'正在编译

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

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

[_Val_types = std :: _ Simple_types]

错误C2065:'elt':未声明的标识符

Die*_*ühl 6

问题是编译器无法推断出类型,t因为它是通过模板模板参数间接确定的.但是,实际上首先没有必要做这样的事情!以下工作正常:

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

(好吧,因为我没有Json你正在使用的库,我没有尝试编译它,但我认为应该没问题).