为什么我会在赋值语句中得到“没有匹配'getVector'的匹配函数”错误?如何解决错误说“没有匹配的XXX函数调用”?
template <typename T>
vector<T> getVector(int);
int main() {
auto myVector = getVector(5);
...
}
template <typename T>
vector<T> getVector(int size) {
...
}
为什么我会在赋值语句中得到“没有匹配'getVector'的匹配函数”错误?如何解决错误说“没有匹配的XXX函数调用”?
template <typename T>
vector<T> getVector(int);
int main() {
auto myVector = getVector(5);
...
}
template <typename T>
vector<T> getVector(int size) {
...
}
看看你的编译器说什么!它试图帮助你。
main.cpp:7:21: error: no matching function for call to 'getVector'
然后:
main.cpp:4:16: note: candidate template ignored: couldn't infer template argument
'T' std::vector<T> getVector(int);
的错误是很清楚的:编译器看到你的getVector
功能,但你从来没有说过一个“混凝土”式的以替代T
:编译器不知道你希望这个向量被保存,所以它只是忽略那个函数模板。
你想在矢量中存储什么样的值?整数例如?然后:
auto myVector = getVector<int>(5);
^give a type here
谢谢!这解释了我的困惑。但是我还有一个问题,如果我不知道应该替代T的“具体”类型怎么办?就像,我想从文件中获取数字,但我不知道这些数字是什么类型。 – 2014-10-02 23:38:33
模板是一个*编译时*结构:如果您在编译时不知道'T',那么您不能实例化模板。但是你可以使用一个可以容纳任何东西的类型:例如查看'boost :: any'。这样你就可以拥有一个'std :: vector
您定义getVector()
为需要一个模板参数T
函数模板。需要以某种方式提供该模板参数。如果没有T
的推导或显式提供,则无法调用该函数。
例如,如果你正在返回矢量持有整数,您可以T
像这样提供int
:
auto myVector = getVector<int>(5);
什么是你想要返回向量的类型? – 0x499602D2 2014-10-01 23:46:09