【问题标题】:C++ Templates Error: no matching function for call std::vector<int, std::allocator<int> >C++ 模板错误:调用 std::vector<int, std::allocator<int> 没有匹配函数
【发布时间】:2012-06-18 14:29:06
【问题描述】:

我无法弄清楚为什么我收到以下代码的错误:

template <typename T>
class Test{
    void foo(vector<T>& v);
};

template <typename T>
void Test<T>::foo(vector<T>& v){
    //DO STUFF
}

int main(){
      Test<int> t;
      t.foo(vector<int>());
}

这是错误:

main.cpp: In function ‘int main()’:
main.cpp:21:21: error: no matching function for call to ‘Test<int>::foo(std::vector<int, std::allocator<int> >)’
main.cpp:21:21: note: candidate is:
main.cpp:14:6: note: void Test<T>::foo(std::vector<T>&) [with T = int]
main.cpp:14:6: note:   no known conversion for argument 1 from ‘std::vector<int, std::allocator<int> >’ to ‘std::vector<int, std::allocator<int> >&’

我做错了什么?

【问题讨论】:

    标签: c++ templates vector


    【解决方案1】:

    您不能将临时对象绑定到非const 引用。

    要么将您的签名更改为:

    void foo(vector<T> const& v);
    

    或者不通过临时:

    vector<int> temp;
    t.foo(temp);
    

    【讨论】:

      【解决方案2】:

      您似乎正试图将您的类分成声明(通常放在 .h 文件中的东西)和定义(放在 .cpp 文件中的东西)。但是,由于模板的性质,通常将类的所有代码放在标题中。模板代码不能预编译(即不能编译成共享库或DLL),因为使用代码时类型信息会发生变化。

      TLDR:上面写着“// DO STUFF”的部分...将其放在标题中并删除相应.cpp中可能包含的任何内容。

      【讨论】:

      • 我的原始代码已经在我的标题中。我刚刚做了一个 sn-p 来重现错误。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-12-05
      • 1970-01-01
      • 2020-07-02
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多