为什么C++找不到模板功能?
Why doesn't C++ find template function?
为什么我会收到编译错误no matching function for call to `f( __gnu_cxx::__normal_iterator > >)'
?
#include <vector>
template<typename T>
void f(const typename std::vector<T>::iterator &) {}
void g() {
std::vector<int> v;
f<int>(v.end()); // Compiles.
f(v.end()); // Doesn't compile, gcc 4.3 can't find any match.
}
最终,我想编写一个函数,该函数仅接受一个矢量迭代器,并且无法编译(带有有意义的错误(以进行其他任何操作。所以template<typename T>void f(const T&) {}
不是一个好的解决方案,因为它也可以针对其他类型的编译。
不能从嵌套类型推断模板参数。例如,想想std::vector<T>::size_type
总是std::size_t
:编译器将如何解决歧义?我意识到在你的例子中情况并非如此,但同样的原则也适用。例如,std::vector<T>
的迭代器类型可以是T*
也可以是std::array<T, N>
的迭代器类型。
G++ 4.8 给出了更完整的消息:http://ideone.com/ekN3xs
note: template argument deduction/substitution failed:
note: couldn't deduce template parameter ‘T’
f
不直接采用T
(如"const T&
"(或T
清晰的类型(如"const std::vector<T>&
"(而是嵌套依赖类型(此处std::vector<T>::iterator
(,因此模板类型T
无法从参数中自动推导出来。
编辑:Dietmar Kühl的回答给出了一个很好的理由例子。
对于您的"最终"部分,请检查如何在编译时检查类型是否为 std::vector::迭代器?(接受的答案使用一些 C++11 类型,但您可以使用 C++03 等效类型,例如来自 Boost(
相关文章:
- 在执行其他功能的同时播放动画(LED矩阵和Arduino/ESP8266)
- 多态性和功能结合
- 带内存和隔离功能的SQLite
- 在CMakeLists.txt的安装功能中使用.cmake文件有什么用
- 类模板的成员功能的定义在单独的TU中完全专业化
- 有没有一种方法可以创建一个带有哈希表的数据库,该哈希表具有恒定时间查找功能
- 如何在C++中获得"静态纯虚拟"功能?
- 两个文件使用彼此的功能-如何解决
- 我应该实现右值推送功能吗?我应该使用std::move吗
- QML按钮点击功能执行顺序
- 无法理解此 return 语句的功能,没有它就会发生运行时错误
- 有没有可能有一个只有ADL才能找到的非好友功能
- 功能样式转换从 'int' 到 'ItemType' 的匹配转换
- 文件系统:复制功能的速度秘诀是什么
- 在用于格式4的arm模拟器中实现功能时的一个问题
- 如何在Directwrite中获得给定字体的可用OpenType功能
- 对可变参数使用声明.如何选择正确的功能
- 询问在设计我的手臂模拟器功能表示格式1
- 功能原型的目的
- 这里在 Linux 中具有"CreatePipe"和"CreateProcessW"功能吗?