模板向导的难题

Dim*_* C. 1 c++ templates

我想做以下事情:

const int someInt;
const std::vector<int> someIntList;
const std::vector<std::vector<int>> someNestedIntList;

Marshall(someInt); // trivial case
Marshall(someIntList); // difficult case
Marshall(someNestedIntList); // difficult case
Run Code Online (Sandbox Code Playgroud)

我尝试了以下方法:

template<std::vector<class Element>> 
void Marshall(const std::vector<Element>& toBeMarshalled)
{
    for (int i=0; i<toBeMarshalled.size(); ++i)
        Marshall<Element>(toBeMarshalled[i]);
}
Run Code Online (Sandbox Code Playgroud)

遗憾的是,这不会编译,我找不到合适的语法.

请注意,必须只有一个模板参数,否则嵌套列表的编组将不起作用.

更新:感谢FredOverflow的回答,我找到了我想要的东西.我忘了标准库中的所有容器类都有一个value_type typedef.这可以用作我的问题的解决方法:

template <class Container> 
void Marshall(const Container& toBeMarshalled)
{
    for (UINT32 i=0; i<toBeMarshalled.size(); ++i)
        Marshall<Container::value_type>(toBeMarshalled);
}
Run Code Online (Sandbox Code Playgroud)

这是一个补丁,但我认为这已经足够了.

sbi*_*sbi 7

您的模板有两个问题:

  1. 模板声明是错误的.您只在此处列出模板参数,而不是函数参数类型.此外,>>被解析为移位运算符.
  2. std::vector有两个模板参数.虽然在日常工作中,你很少会使用第二个,它仍然存在,并应列出,或者如果有谁试图与使用模板会失败std::vector,不使用默认的分配器.

这适用于所有std::vector实例:

template< typename T > 
void Marshall(const T& toBeMarshalled)
{
  // ...
}

template< typename T, class A > 
void Marshall(const std::vector<T,A>& toBeMarshalled)
{
    for (typename std::vector<T,A>::size_type i=0; i<toBeMarshalled.size(); ++i)
        Marshall(toBeMarshalled[i]);
}
Run Code Online (Sandbox Code Playgroud)