假设std::vector
没有value_type
。是可以写出一个模板来推导出value_type
?或者更一般的,给出T<X>
,我怎么能推导出X
?如何获取模板模板参数的模板参数?
很天真..
template <template <typename X> T>
void test(T<X> t) {
X x;
}
将可能使任何人谁知道一点关于模板嘲笑我的愚蠢的尝试,当实例化这样的:
int main() {
std::vector<int> x;
test(x);
}
创建以下错误:
error: expected ‘class’ before ‘T’
template < template<typename X> T>
^
error: ‘X’ was not declared in this scope
void test(T<X> u) {
^
error: template argument 1 is invalid
void test(T<X> u) {
^
In function ‘void test(int)’:
error: ‘X’ was not declared in this scope
X x;
^
error: expected ‘;’ before ‘x’
X x;
^
In function ‘int main()’:
error: no matching function for call to ‘test(std::vector<int>&)’
test(x);
^
note: candidate is:
note: template<template<class X> class T> void test(int)
void test(T<X> u) {
^
note: template argument deduction/substitution failed:
note: cannot convert ‘x’ (type ‘std::vector<int>’) to type ‘int’
编辑:第一个很容易修复,但修复它不会影响o thers ...
PS:我想我有一个小小的误解,因为std::vector<int>
不是一个模板,而是一个具体的类型。不过,我仍然想知道是否有办法从someTemplate<int>
获得int
以及一些模板魔法。
如果我记得正确的,你必须在嵌套模板中使用'class'。类似于'template class T>'。 – pingul
请注意'std :: vector'具有第二个(默认)模板参数。 – Jarod42
种类的工作,但如果你只是使用容器,你可以得到一个迭代器并使用'std :: iterator_traits'。 – NathanOliver