[英]c++ template argument in vector return value
我有一個特定的問題,我在所有有關模板成員函數的問題中都找不到真正的答案。 我想編寫一個獲取我一些數據並將其作為特定類型的向量返回的函數。
我有以下幾點:
#include <vector>
class testClass
{
public:
template <typename T> std::vector<T> getData(int column);
};
template <typename T> std::vector<T> testClass::getData(int column){
std::vector<T> returnData;
return returnData;
}
並調用該函數:
int main()
{
testClass t;
std::vector<int> data = t.getData(0);
return 0;
}
編譯時出現錯誤:
../templateTest/main.cpp:9:31: error: no matching member function for call to 'getData'
std::vector<int> data = t.getData(0);
~~^~~~~~~
../templateTest/testclass.h:8:42: note: candidate template ignored: couldn't infer template argument 'T'
template <typename T> std::vector<T> getData(int column);
^
好的,因此無法從返回類型的模板中獲取模板參數。 為了解決這個問題,我嘗試在調用中包括template參數:
int main()
{
testClass t;
std::vector<int> data = t.getData<int>(0);
return 0;
}
這可以編譯,但給我一個鏈接器錯誤:
Undefined symbols for architecture x86_64:
"std::__1::vector<int, std::__1::allocator<int> > testClass::getData<int>(int)", referenced from:
_main in main.o
最后一種嘗試是在函數定義中也包含template參數:
class testClass
{
public:
template <typename T> std::vector<T> getData<T>(int column);
};
但是,這不會編譯...:
../templateTest/testclass.h:8:42: error: member 'getData' declared as a template
template <typename T> std::vector<T> getData<T>(int column);
我可以嘗試做什么?
謝謝!!
將實現放在標頭中確實可行。 但是,如果您希望在.cpp中實現。 為您計划使用的每個實現添加最后一行。
#include "testclass.h"
template <typename T> std::vector<T> testClass::getData(int column){
std::vector<T> returnData;
return returnData;
}
template std::vector<int> testClass::getData(int column);
您很可能只是在.cpp文件而不是.h中定義了功能模板。 這就是為什么在t.getData<int>(0)
出現鏈接器錯誤的原因。 如果是這樣,請閱讀這篇文章 。
我只是運行了以下程序,它編譯良好。
#include <vector>
class testClass
{
public:
template <typename T> std::vector<T> getData(int column);
};
template <typename T> std::vector<T> testClass::getData(int column){
std::vector<T> returnData;
return returnData;
}
int main()
{
testClass t;
std::vector<int> data = t.getData<int>(0);
return 0;
}
使用模板時,您不應為功能使用單獨的cpp文件。 確保將定義放在頭文件中。 這是必需的,因為可以在模板中傳遞任何類型,並且編譯器將需要為每種不同的類型創建該函數的新版本。 在處理模板時,我通常只在類內部定義函數。
class testClass
{
public:
template <typename T> std::vector<T> getData(int column){
std::vector<T> returnData;
return returnData;
}
};
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.