c++ - 我可以退回不同类型的模板化容器吗?

标签 c++ templates generic-programming template-templates

我怎样才能创建一个像这样的函数?我似乎无法正确声明返回类型。

template <typename C, typename T0, typename T1>
typename C<T1> 
convert_container(const C<T0>& container, T1 value) {
  C<T1> new_container;
  // Do some stuff...
  return new_container;
}

std::vector<int> vec0;
const auto& vec1 = convert_container(vec0, float(2.0f)); // Produce a vector of floats

std::list<int> lst0;
const auto& lst1 = convert_container(lst0, float(2.0f)); // Produce a list of floats

最佳答案

正确的做法是使用template模板参数:

  • C++11:

    template <template<typename...> class C, typename T0, typename T1>
    C<T1> convert_container(const C<T0>& container, T1 value) {
      C<T1> new_container;
      // Do some stuff...
      return new_container;
    }
    
  • C++03(带分配器重新绑定(bind)):

    template <template<typename, typename> class C, typename T0, typename T1, typename Alloc>
    C<T1, typename Alloc::template rebind<T1>::other>
    convert_container(const C<T0, Alloc>& container, T1 value) {
      C<T1, typename Alloc::template rebind<T1>::other> new_container;
      // Do some stuff...
      return new_container;
    }
    
  • C++03(无需重新绑定(bind)):

    template <template<typename, typename> class C, typename T0, typename T1, typename Alloc>
    C<T1, std::allocator<T1> > convert_container(const C<T0, Alloc>& container, T1 value) {
      C<T1, std::allocator<T1> > new_container;
      // Do some stuff...
      return new_container;
    }
    

关于c++ - 我可以退回不同类型的模板化容器吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21782874/

相关文章:

c++ - 以编程方式推广 QWidget

C++ 从文本文件执行代码

c++ - 使用cmake -G时如何指定输出路径?

c++ - 为什么模板内部的类型检查更严格?

c++ - 动态分配模板类时出现编译器错误,其中类型是模板类型的另一个对象

generics - 如何在 Haxe (haxe3) 中编写通用比较函数

scala - 部分应用的通用函数 "cannot be cast to Nothing"

.net - 在没有安装 VS 的情况下运行 msbuild

c++ - typedef 和 using 会导致模板实例化吗?

c++ - 继承和虚函数与泛型编程