【问题标题】:no known conversion for templated vs const non-templated vector没有已知的模板化与 const 非模板化向量的转换
【发布时间】:2016-05-21 18:21:42
【问题描述】:

在我的实际代码中,我包含了一个库,一旦我这样做,它就开始崩溃。我设法将其中一些代码提取到这个最小的示例中,它演示了相同类型的错误:

// g++ -std=c++11 -g -o test-classcall.exe test-classcall.cpp

#include <iostream>
#include <vector>
#include <stdio.h>

class Cat
{
  public:
    int Age;
    Cat() : Age(0) {}
};

std::vector<Cat> myPCats;

typedef std::vector<Cat> TDVectCats;
TDVectCats myTDCats;

void loopSomeCats() {
  printf("this function just to cause searching for matching calls\n");
}

void loopSomeCats(TDVectCats& incats) {
  std::vector<Cat>::iterator iter;
  for(iter = incats.begin(); iter != incats.end(); iter++) {
    printf("hm\n");
  }
}

const std::vector<Cat> & getSomeCats() {
  return myPCats;
}

void doSomething() {
  loopSomeCats(getSomeCats());
}

int main() {
  myTDCats.push_back(Cat());
  myTDCats.push_back(Cat());
  myPCats.push_back(Cat());

  doSomething();
  std::cout << "Hello World! " << std::endl;
  return 0;
}

结果是:

$ g++ -std=c++11 -g -o test-classcall.exe test-classcall.cpp
test-classcall.cpp: In function ‘void doSomething()’:
test-classcall.cpp:36:29: error: no matching function for call to ‘loopSomeCats(const std::vector<Cat>&)’
   loopSomeCats(getSomeCats());
                             ^
test-classcall.cpp:36:29: note: candidates are:
test-classcall.cpp:20:6: note: void loopSomeCats()
 void loopSomeCats() {
      ^
test-classcall.cpp:20:6: note:   candidate expects 0 arguments, 1 provided
test-classcall.cpp:24:6: note: void loopSomeCats(TDVectCats&)
 void loopSomeCats(TDVectCats& incats) {
      ^
test-classcall.cpp:24:6: note:   no known conversion for argument 1 from ‘const std::vector<Cat>’ to ‘TDVectCats& {aka std::vector<Cat>&}’

让我特别困惑的是,最后一次“参数 1 从 'const std::vector' 到 'TDVectCats& {aka std::vector&}' 的未知转换”,好像它不能仅仅因为typedef? 将某事物的向量转换为同一事物的向量?或者它可能与const 有关 - 但我根本看不到我需要更改什么,以便像loopSomeCats(getSomeCats()); 这样的调用成功......

【问题讨论】:

    标签: c++ c++11 vector typedef


    【解决方案1】:

    您不能将对 const 对象的引用传递给非常量引用。

    loopSomeCatsstd::vector&lt;Cat&gt;&amp; 作为参数,而您想将 const std::vector&lt;Cat&gt;&amp; 传递给它,但这是不可能的。

    const 表示您不希望任何人修改返回值,但如果您将它传递给只接受非常量引用的函数,那么理论上该函数可以 修改引用,而你不希望这样。

    如果你想修改返回值,你应该删除const

    【讨论】:

    • 非常感谢@Rakete1111 - 成功了;干杯!
    猜你喜欢
    • 1970-01-01
    • 2021-09-02
    • 2019-10-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多