代码之家  ›  专栏  ›  技术社区  ›  Mutating Algorithm

将特定类型的迭代器传递给模板函数[duplicate]

  •  0
  • Mutating Algorithm  · 技术社区  · 7 年前

    这为什么不能在C++中工作?
    foo 的参数 std::vector<T>::iterator 像这样,最好的解决办法是什么?

    #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’
    
    0 回复  |  直到 12 年前
        1
  •  6
  •   James Kanze    12 年前

    这个 T 这是在一个非推论的背景下。为什么 上下文不被推断是因为当您将某个类型传递给 函数时,编译器必须实例化每个 可能的 std::vector 特定的翻译单位)为了找到一个

    标准::矢量 因为类的语义 由标准定义。但总的来说, TemplateClass<T>::NestedType 任何东西,编译器对此无能为力。

        2
  •  2
  •   Puppy    12 年前

    简单。

    struct X {};
    template<> class std::vector<X> {
        typedef std::vector<int>::iterator iterator;
    };
    

    哎呀。

    模板是图灵完成。您要求编译器从结果中推断参数。这在一般情况下是不可能的,甚至忽略了非一对一通信的可能性。