我试图做一个快速的实用工具类,通过构图来扩展std::vector
。为此,我希望尽可能通用。声明并在一个单一的文件中实现时模板化成员函数的声明和实现
类效果很好(即main.cpp中):
的main.cpp
#include <iostream>
#include <algorithm>
#include <vector>
template<typename T>
class FVector {
public:
FVector(std::vector<T> vector): _vector(vector) {}
template <typename unaryOperation>
void forEach(unaryOperation op) {
std::for_each(_vector.begin(),_vector.end(),op);
};
private:
std::vector<T> _vector;
};
int main(int argc, const char * argv[]) {
auto printInt = [](int i){ std::cout << i << std::endl; };
std::vector<int> numbers{1, 2, 3, 4, 5};
FVector<int> fNumbers{numbers};
fNumbers.forEach(printInt);
return 0;
}
但是,当我试图把这个类在它自己的.h和.cpp文件,编译器将不会找到构造函数或函数。
FVector.h
...
#include <vector>
template<typename T>
class FVector {
public:
FVector(std::vector<T>);
template <typename unaryOperation>
void forEach(unaryOperation);
private:
std::vector<T> _vector;
};
...
FVector.cpp
#include "FVector.hpp"
#include <algorithm>
template <typename T>
FVector<T>::FVector(std::vector<T> vector): _vector(vector) {}
template <typename T>
template <typename unaryOperation>
void FVector<T>::forEach(unaryOperation op) {
std::for_each(_vector.begin(),_vector.end(),op);
}
的main.cpp
#include <iostream>
#include "FVector.hpp"
int main(int argc, const char * argv[]) {
auto printInt = [](int i){ std::cout << i << std::endl; };
std::vector<int> numbers{1, 2, 3, 4, 5};
FVector<int> fNumbers{numbers};
fNumbers.forEach(printInt);
return 0;
}
错误
函数 'FVector ::的forEach <(拉姆达在嗒嗒/ main.cpp中:95:21)>' 具有 内部连接,但没有定义
显然,在我的语法的东西是非常错误的,但我找不到如何声明/实现这些功能。
谢谢!
您需要在头文件中定义'forEach'。另见: http://stackoverflow.com/questions/115703/storing-c-template-function-definitions-in-a-cpp-file –
@VittorioRomeo所以没有办法分开声明和实现? – whitelionV
是的,你可以有一个额外的“内联”头文件并包含它。这是一个非常普遍讨论的话题,请搜索它 –