首页 > 解决方案 > 为什么在这个模板模板参数中参数推导不起作用

问题描述

我有以下模板函数,它以模板模板参数作为其参数。

template<typename T, 
         template <typename... ELEM> class CONTAINER = std::vector>
void merge(typename CONTAINER<T>::iterator it )
{
   std::cout << *it << std::endl;
}

以下代码使用此代码。

std::vector<int> vector1{1,2,3};
merge<int>(begin(vector1));

它按预期工作,但是当我使用

merge(begin(vector1));

它不能推断出 的类型T

我认为它可以从std::vector<int>::iterator it;as推断类型int

为什么编译器不能推断类型?

标签: c++templatesc++14template-argument-deductiontemplate-templates

解决方案


我认为它可以从std::vector<int>::iterator it;int 中推断出类型。

为什么编译器不能推断类型?

不。

编译器不能:查找“非推断上下文”以获取更多信息。

并且期望扣除是不合理的。

假设一个类如下

template <typename T>
struct foo
 { using type = int; };

类型type始终 int; 不管是什么T类型。

并假设一个函数如下

template <typename T>
void bar (typename foo<T>::type i)
 { }

接收一个int值(typename foo<T>::type总是int)。

T应该从以下调用中推断出哪种类型?

bar(0);

推荐阅读