【发布时间】:2017-08-23 09:32:13
【问题描述】:
我有一个具体的问题,我无法在所有有关模板成员函数的问题中找到答案。我想编写一个函数来获取一些数据并将其作为特定类型的向量返回。
我有以下几点:
#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);
^
好的,所以它无法从返回类型的模板中获取模板参数。为了解决这个问题,我尝试在调用中包含模板参数:
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
最后一个尝试是在函数定义中也包含模板参数:
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);
【问题讨论】:
-
Click 效果很好
-
是的,我也刚刚使用 GCC 7 进行了测试。
-
旁注:你确定是函数,而不是应该模板化的类吗?
-
嗯...我用clang。是的,这就是功能。在真正的实现中,我需要那个函数来返回我需要的任何东西。实际的类代表一大堆不同类型的数据。
标签: c++ function templates return