[英]no known conversion for templated vs const non-templated vector
在我的實際代碼中,我包含了一個庫,一旦這樣做,它便開始崩潰。 我設法將一些代碼提取到這個最小的示例中,該示例演示了相同類型的錯誤:
// 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 <Cat>'轉換為'TDVectCats&{aka std :: vector <Cat>&}''”,就好像它無法轉換向量一樣只是因為typedef
導致某物進入同一物的向量? 或者它可能與const
-但我根本看不到需要更改什么,才能進行loopSomeCats(getSomeCats());
類的調用loopSomeCats(getSomeCats());
成功...
您不能const
對象的引用傳遞給非const引用。
loopSomeCats
將std::vector<Cat>&
作為參數,並且您想向其傳遞const std::vector<Cat>&
,但這是不可能的。
const
表示您不希望任何人修改返回值,但是如果將其傳遞給僅接受非const引用的函數,則理論上該函數可以修改該引用,而您不希望這樣做。
如果要修改返回值,則應刪除const
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.