Cur*_*ous 4 c++ templates types variadic-templates c++11
我试图使用模板元编程在参数包中的指定索引处获取类型.我有下面的代码,但由于某种原因它总是返回一个int,有人可以告诉我我做错了什么?
#include <string>
#include <iostream>
using std::cout;
using std::endl;
using std::string;
template <int current_index, typename... Vs>
struct TypeForIndex {};
template <int current_index, typename Head, typename... Tail>
struct TypeForIndex<current_index, Head, Tail...> : private TypeForIndex<current_index + 1> {
using type = Head;
};
template <int current_index, typename Tail>
struct TypeForIndex<current_index, Tail> {
using type = Tail;
};
int main() {
TypeForIndex <2, int, double, string>::type a {"hello"};
cout << a << endl;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
上面的代码应该string作为类型返回,a但不知何故它总是一个int
TypeForIndex<2, int, double, string>
Run Code Online (Sandbox Code Playgroud)
好的,模式匹配时间.首先,它明显匹配
template <int current_index, typename... Vs>
struct TypeForIndex {};
Run Code Online (Sandbox Code Playgroud)
所以没有错误.它是否与其他专业相匹配?
A:
template <int current_index, typename Head, typename... Tail>
struct TypeForIndex<current_index, Head, Tail...>
Run Code Online (Sandbox Code Playgroud)
B:
template <int current_index, typename Tail>
struct TypeForIndex<current_index, Tail>
Run Code Online (Sandbox Code Playgroud)
那么,它匹配(A)而不是(B).
用(A),current_index是2,Head是int和Tail...是double, std::string.
template <int current_index, typename Head, typename... Tail>
struct TypeForIndex<current_index, Head, Tail...> : private TypeForIndex<current_index + 1> {
using type = Head;
};
Run Code Online (Sandbox Code Playgroud)
现在,这private TypeForIndex<current_index + 1>几乎没用.它总是只匹配主要特化,它具有一个空体,它是私有的,所以没有人会注意到它.我们可以删除它而不会改变程序的行为.
template <int current_index, typename Head, typename... Tail>
struct TypeForIndex<current_index, Head, Tail...> {
using type = Head;
};
Run Code Online (Sandbox Code Playgroud)
如上所述,Head是int.所以我们得到了type=int.
就是这样.这就是为什么type是int.
...
你做错了什么几乎是一切?除了编译(即,存在与签名匹配的主要专业化)之外,您提供的代码与您在文本中描述的内容无关.甚至current_index+1是一个我不希望存在于代码中的字符串,它可以执行文本描述的内容.
抛出除主要专业化之外的所有内容,这有效:
template <typename Head, typename... Tail>
struct TypeForIndex<0, Head, Tail...> {
using type = Head;
};
template <int current_index, typename Head, typename... Tail>
struct TypeForIndex<current_index, Head, Tail...>:
TypeForIndex<current_index-1, Tail...>
{};
Run Code Online (Sandbox Code Playgroud)
type如果传递过大的索引,它就没有正确的定义.
我也会用a size_t而不是int.
| 归档时间: |
|
| 查看次数: |
210 次 |
| 最近记录: |