【发布时间】:2018-08-25 23:19:01
【问题描述】:
我正在尝试使用模板元编程实现元组,但在索引函数get 上遇到问题。 Tuple 类型的实现是这样的:
template<typename A, typename... B>
class Tuple : Tuple<B...> {
private:
A val;
public:
using Base = Tuple<B...>;
Base* base() {
return static_cast<Base*>(this);
}
const Base* base() const {
return static_cast<const Base*>(this);
}
Tuple(A a, B... b): Base(b...), val(a) { }
A first() {
return val;
}
};
template<class A>
class Tuple<A> {
private:
A val;
public:
Tuple(A a): val{a} {}
A first() {
return val;
}
};
get结构的实现是:
template<int N, class... A>
struct get {
select<N,A...> operator()(Tuple<A...> t) {
return get<N-1>()(t.base());
}
};
template<class R, class... A>
struct get<0> {
R operator()(Tuple<R, A...> t) {
return t.first();
}
};
这是编译器给我的错误:
tuple.cpp:53:8: error: partial specialization of 'get' does not use any of its template parameters
struct get<0> {
^
1 error generated.
为什么会出现此错误?我该如何纠正?
注意:select<N,A...> 是一个类型函数,它从A 中选择第 N 个索引处的类型。
【问题讨论】:
-
我认为只要将
template <class R, class ... A>更改为template <>并将Tuple<R, A...>更改为Tuple<0>即可解决。
标签: c++ c++11 variadic-templates template-meta-programming template-specialization