c++ - C++ 中的模板和高阶种类

标签 c++ templates higher-kinded-types

我正在尝试编写一个函数,它接受两个包含相同类型的容器,例如两个 std::vector<int> s,或 std::list<int>和一个 std::vector<int> . (但不是 std::vector<int>std::vector<double> !)

因为我不太确定应该怎么做,所以我决定先写一个测试程序:

#include <iostream>
#include <vector>
#include <list>
#include <algorithm>

struct vector_wrapper
{
  template <typename T>
  struct instance_wrapper
  {
    typedef typename std::vector<T> instance;
  };
};

struct list_wrapper
{
  template <typename T>
  struct instance_wrapper
  {
    typedef typename std::list<T> instance;
  };
};

template <typename T, typename C1, typename C2>
void move(typename C1::instance_wrapper<T>::instance& c1, typename C2::instance_wrapper<T>::instance& c2) // line 29
{
  while (c1.size() > 0)
  {
    c2.push_front(c1.back());
    c1.pop_back();
  }
}

int main()
{
  std::vector<int> v;
  std::list  <int> l;

  v.reserve(10);
  for (int i = 0; i < 10; ++i)
    v.push_back(i);

  move<int, vector_wrapper, list_wrapper>(v, l);

  std::for_each(l.begin(), l.end(),
    [] (int i) { std::cout << i << " "; }
  );

  std::cout << std::endl;

  return 0;
}

此代码使用 -std=c++11 给出了 g++ 4.7 的以下编译时错误标志:

metaclass.cpp:29:24: error: non-template 'instance_wrapper' used as template
... more ...

为什么编译器不能正确识别instance_wrapper作为模板?

最佳答案

编译器已经告诉你出了什么问题(来自 ideone 的错误):

prog.cpp:25:24: error: non-template 'instance_wrapper' used as template
prog.cpp:25:24: note: use 'C1::template instance_wrapper' to indicate that it is a template

使用 C1::template instance_wrapper 而不是 C1::instance_wrapper - 同样地,对 C2::instance_wrapper 做同样的事情:

template <typename T, typename C1, typename C2>
void move(typename C1::template instance_wrapper<T>::instance& c1, 
    typename C2::template instance_wrapper<T>::instance& c2)
{
    // ...

因为C1是模板,编译器无法推断instance_wrapper是模板,将其视为非模板类​​型。

请,请阅读所有编译器输出。不仅仅是逐行阅读。编译器通常会指出前几行或后几行中的错误,就像在本例中,当它已经给您答案时!

关于c++ - C++ 中的模板和高阶种类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11278393/

相关文章:

c++ - jconsole 能否用于识别 JNI C++ 对象中的内存泄漏?

c++ - 隐藏c plus plus程序中的bash代码

scala - Scala 中扁平元组的高阶操作

c++ - 使用来自另一个包的少量 C++ 级代码

java - 在我的 xhtml 中使用模板 (jsf) 后,commandLink 和 CommandButton 标记不会调用任何操作

templates - meteor 整页模板

c++ - 为什么类中不允许函数模板特化?

scala - 高级类型的辅助模式

Java Generic获取类型参数

c++ - CMake 无法链接到 vcpkg 库