pyo*_*yon 3 c++ templates higher-kinded-types
我正在尝试编写一个函数,它接受两个相同包含类型的容器,例如,两个std::vector<int>s,或a std::list<int>和a std::vector<int>.(但不是a std::vector<int>和a 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;
}
Run Code Online (Sandbox Code Playgroud)
这段代码使用-std=c++11标志给我带来g ++ 4.7的以下编译时错误:
metaclass.cpp:29:24: error: non-template 'instance_wrapper' used as template
... more ...
Run Code Online (Sandbox Code Playgroud)
为什么编译器没有正确识别instance_wrapper为模板?
编译器已经告诉你出了什么问题(来自ideone的错误):
prog.cpp:25:24:错误:非模板'instance_wrapper'用作模板
prog.cpp:25:24:注意:使用'C1 :: template instance_wrapper'表示它是模板
使用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)
{
// ...
Run Code Online (Sandbox Code Playgroud)
这是因为C1模板和编译器不能推断出它instance_wrapper是模板并将其视为非模板类型.
请,请阅读所有编译器输出.不仅仅是逐行.通常编译器会说出前一行或后续行中的错误,就像在这种情况下,当它已经给你答案时!