假设
非常幼稚的方法是...
创建以下错误:
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’
编辑:第一个问题很容易解决,但修复它不会影响其他问题...
PS:我认为我有一个小误解,因为std::vector<int>
不是一个模板,而是一个具体类型。然而,我仍然想知道是否有一种方法可以使用一些模板魔法从someTemplate<int>
中获取int
。
class
。类似这样:template <template <typename X> class T>
。 - pingulstd::vector
有第二个(默认)模板参数。 - Jarod42std::iterator_traits
。 - NathanOliver