简体   繁体   English

为什么我不能通过 std::vector<mytype> 到这个带有模板模板参数的 function ?</mytype>

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

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.我是 C++ 模板的新手,我想编写一个模板 function,它根据其参数返回单个 object 或对象向量。

I have a configuration class that holds key/value pairs.我有一个包含键/值对的配置 class 。 Say I have the key "parent.child.1", it should return a single object with id=1.假设我有密钥“parent.child.1”,它应该返回一个 id=1 的 object。 If I have the key "parent.child" then it should return all the objects under child.如果我有键“parent.child”,那么它应该返回子项下的所有对象。 All the objects under child are same type but different childs may hold different objects. child 下的所有对象都是相同的类型,但不同的 child 可能持有不同的对象。

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.我可以通过为每种类型专门设置 getParameter function 来做到这一点,乘以 2,但我认为如果我使用模板,我可以为每种不同类型减少大量样板代码。

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):我已经关注了另一个SO question,并在我的代码中使用了它(我使用的是 c++11,所以它有点不同):

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);当我调用getParameter<std::vector<MyObject>>(key, vectorValue);时,它无法替换这两个函数. . Why is that?这是为什么?

The 2nd getParameter takes two template parameters, but getParameter<std::vector<MyObject>>(...) specifies only one template argument then it won't be selected.第二个getParameter接受两个模板参数,但getParameter<std::vector<MyObject>>(...)只指定一个模板参数,然后它不会被选中。

I think just making the 2nd getParameter taking one template parameter should be fine.我认为让第二个getParameter采用一个模板参数应该没问题。 eg例如

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 .如果要获取元素类型,可以使用std::vector的成员类型value_type ,例如typename T::value_type

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM