为什么迭代器类型推导失败? [英] Why does iterator type deduction fail?

查看:104
本文介绍了为什么迭代器类型推导失败?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么这在C ++中不起作用?
为什么不能像这样将foo的参数限制为std::vector<T>::iterator?最佳的解决方法是什么?

Why does this not work in C++?
Why can't I restrict foo's parameter to std::vector<T>::iterator like this, and what is the best workaround?

#include <vector>

template<class T>
void foo(typename std::vector<T>::iterator) { }

int main()
{
    std::vector<int> v;
    foo(v.end());
}

错误是:

In function ‘int main()’:
     error: no matching function for call to ‘foo(std::vector<int>::iterator)’
     note: candidate is:
    note: template<class T> void foo(typename std::vector<T>::iterator)
    note:   template argument deduction/substitution failed:
     note:   couldn’t deduce template parameter ‘T’

推荐答案

不起作用的主要原因是因为sandard表示 T在非推论上下文中.之所以 不能推断上下文是因为当您将某种类型传递给 函数,编译器将不得不实例化每个单个 可能的std::vector(包括此类型中不存在的类型 特定的翻译单元),以便尝试找到其中一个 有对应的类型.

The main reason it doesn't work is because the sandard says that the T here is in a non-deduced context. The reason why the context is not deduced is because when you pass some type to the function, the compiler would have to instantiate every single possible std::vector (including for types not present in this particular translation unit) in order to try to find one which had a corresponding type.

当然,对于std::vector,编译器可能包含 由于类的语义,使这项工作起作用的一些魔术 由标准定义.但是一般来说 TemplateClass<T>::NestedType可以是一个typedef,从字面上看 任何事情,编译器对此无能为力.

Of course, in case of std::vector, the compiler could contain some magic to make this work, since the semantics of the class are defined by the standard. But generally, TemplateClass<T>::NestedType can be a typedef to literally anything, and there's nothing the compiler can do about it.

这篇关于为什么迭代器类型推导失败?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆