[英]Templated class with templated static member function no match for prototype in implementation
在制作图书馆时,我遇到了以下问题:
我们有四个文件:
以下是每个文件的内容
#include <iostream>
#include <vector>
#include "nsp/nsp.hpp"
using namespace std;
int main(){
vector<int> v = {0, 1};
nsp::A<int> a = nsp::A<int>::from(v.begin(), v.end());
cout << a.getElem();
return 0;
}
#ifndef NSP_HPP
#define NSP_HPP
namespace nsp{};
#include "A.h"
#endif
#ifndef NSP_A_H
#define NSP_A_H
namespace nsp{
template <class T>
class A{
protected:
T elem;
A();
public:
A(T e);
template <class It>
static A<T> from(It begin, It end);
T getElem();
};
};
#endif
#include "A.h"
template <class T>
nsp::A<T>::A(){}
template <class T>
nsp::A<T>::A(T elem){ this->elem = elem; }
template <class T, class It>
nsp::A<T> nsp::A<T>::from(It begin, It end){
nsp::A<T> tmp;
if(begin != end)
tmp.elem = static_cast<T>(*begin);
return tmp;
};
template <class T>
T nsp::A<T>::getElem(){ return this->elem; }
尽管该代码对我来说似乎是正确的(没有语法错误),并且我使用的IDE(CLion)表示所有成员函数均已实现,但在编译时出现以下错误: (nsp/A.cpp) error: prototype for 'nsp::A<T> nsp::A<T>::from(It, It)' does not match any in class 'nsp::A<T>'
其次是(nsp/Ah) error: candidate is: template<class T> template<class It> static nsp::A<T> nsp::A<T>::from(It, It)
我想知道此错误的原因以及如何解决。
从模板类定义模板成员时,必须编写两次template <...>
:
template <class T>
template <class It>
nsp::A<T> nsp::A<T>::from(It begin, It end){
nsp::A<T> tmp;
if(begin != end)
tmp.elem = static_cast<T>(*begin);
return tmp;
}
但是您还有另一个问题: 模板函数只能在头文件中定义 (除非您希望枚举模板应预先使用的所有类型,否则链接也应对此进行说明)。
您可以在类主体内或在头文件中的类下方定义成员函数。 随便你喜欢什么。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.