【发布时间】:2016-02-11 03:01:00
【问题描述】:
无关紧要。请参阅下面的更新。 我一直在玩 std::stack 并注意到一些奇怪的东西。代码如下:
.h 文件
template<typename Tp> using VecOfRef = std::vector<std::reference_wrapper<Tp>>;
template <typename T>
struct Stack : public std::stack<T,VecOfRef<T>> {};
struct Simple {
std::string txt = "txt";
};
.cpp 文件
int main () {
Simple smpl;
auto vec = VecOfRef<Simple>{std::ref(smpl)};
auto stdStack = std::stack<Simple,decltype(vec)>(vec); //works fine
auto myStack = Stack<Simple>(vec); //error
//to check if a reference is stored
stdStack.push(smpl);
smpl.txt.append("append");
Simple& r = sStack.top();
cout << r.txt << endl;
return 0;
}
错误信息说:
19: 没有匹配的函数式转换 'std::__1::vector, std::__1::allocator > >' 到 '堆栈'
更新:
我一直在玩这个并且设法让代码几乎可以工作:
#include <vector>
#include <string>
#include <stack>
#include <iostream>
#include <functional>
template<typename Tp> using VecOfRef = std::vector<std::reference_wrapper<Tp>>;
template <typename T>
class Stack : public std::stack<T,VecOfRef<T>> {
public:
using std::stack<T,VecOfRef<T>>::stack;
using std::stack<T,VecOfRef<T>>::c;
T& top() {
return c.back().get();
}
};
struct Simple {
std::string txt = "txt";
void print() { std::cout << txt << std::endl; }
};
int main() {
Simple smpl;
Simple smpl_2;
Simple smpl_3;
VecOfRef<Simple> vr {smpl,smpl_2,smpl_3};
// auto myStack = Stack<Simple> (vr); // error
auto myStack = Stack<Simple> ({smpl,smpl_2,smpl_3}); // ok
auto stk = std::stack<Simple,std::vector<std::reference_wrapper<Simple>>>(vr); // ok_2
smpl.txt.append("_append");
smpl_2.txt.append("_append_2");
smpl_3.txt.append("_append_3");
myStack.top().print(); // txt_append_3
myStack.pop();
myStack.top().print(); // txt_append_2
myStack.pop();
myStack.top().print(); // txt_append
return 0;
}
它在 gcc 下编译,但不在 clang 下。错误说:
错误:堆栈:154:43:'std::__1::enable_if' 中没有名为 'type' 的类型; 'enable_if' 不能用于禁用此声明
【问题讨论】:
-
很少有标准类是为公开继承而设计的。
-
你试过
auto myStack = Stack<Simple>(stdStack); -
@Minato 拥有
Stack的意义在于不要使用std::stack(这都是为了教育目的)。
标签: c++ templates c++11 inheritance stack