【问题标题】:Why doesn't C++ find template function?为什么 C++ 找不到模板函数?
【发布时间】:2013-08-18 17:01:48
【问题描述】:

为什么会出现编译错误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&lt;typename T&gt;void f(const T&amp;) {} 不是一个好的解决方案,因为它也可以为其他类型编译。

【问题讨论】:

  • 你有什么问题?编译错误的原因是您没有为模板化函数调用提供类型。即使您提供了int 作为向量类型,您仍然需要指定它以调用f

标签: c++ function templates


【解决方案1】:

您不能从嵌套类型中推断出模板参数。想想,例如,std::vector&lt;T&gt;::size_type,它总是std::size_t:编译器将如何解决歧义?我意识到在您的示例中情况并非如此,但同样的原则适用。比如std::vector&lt;T&gt;的迭代器类型可以是T*,也可以是std::array&lt;T, N&gt;的迭代器类型。

【讨论】:

    【解决方案2】:

    G++ 4.8 给出了更完整的消息:http://ideone.com/ekN3xs

    note:   template argument deduction/substitution failed:
    note:   couldn't deduce template parameter ‘T’
    

    f 不直接采用T(如“const T&amp;”)或T 明确的类型(如“const std::vector&lt;T&gt;&amp;”)而是嵌套的依赖类型(此处为@ 987654331@) 所以模板类型T不能从参数中自动推导出来。

    编辑:Dietmar Kühl's answer 给出了一个很好的理由示例。


    对于您的“最终”部分,请检查 How to check whether a type is std::vector::iterator at compile time?(接受的答案使用一些 C++11 类型,但您可以使用 C++03 等价物,例如来自 Boost)

    【讨论】:

    猜你喜欢
    • 2011-02-26
    • 2023-01-14
    • 2019-11-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多