use*_*497 4 c++ templates template-templates template-argument-deduction c++14
我有以下模板函数,它具有模板模板参数作为其参数。
template<typename T,
template <typename... ELEM> class CONTAINER = std::vector>
void merge(typename CONTAINER<T>::iterator it )
{
std::cout << *it << std::endl;
}
Run Code Online (Sandbox Code Playgroud)
以下代码使用此代码。
std::vector<int> vector1{1,2,3};
merge<int>(begin(vector1));
Run Code Online (Sandbox Code Playgroud)
它按预期工作,但是当我使用
merge(begin(vector1));
Run Code Online (Sandbox Code Playgroud)
无法推断出的类型T。
我认为它可以从std::vector<int>::iterator it;as 推断出类型int。
为什么编译器无法推断类型?
I thought that it could deduce type from
std::vector<int>::iterator it;as int.Why the compiler can't deduce the type?
No.
The compiler can't: look for "non-deduced context" for more information.
And isn't reasonable expecting a deduction.
Suppose a class as follows
template <typename T>
struct foo
{ using type = int; };
Run Code Online (Sandbox Code Playgroud)
where the type type is always int; whatever is the T type.
And suppose a function as follows
template <typename T>
void bar (typename foo<T>::type i)
{ }
Run Code Online (Sandbox Code Playgroud)
that receive a int value (typename foo<T>::type is always int).
Which T type should be deduced from the following call ?
bar(0);
Run Code Online (Sandbox Code Playgroud)