微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

只有静态方法的模板类使用 .cpp 文件实现,给出错误

如何解决只有静态方法的模板类使用 .cpp 文件实现,给出错误

我正在尝试用 C++ 实现一个类,其中包含我可能需要在不同类层次结构中使用的大部分函数(该项目有多个不同的继承树)。

在对 Stack overflowWhy can templates only be implemented in the header file? 上的此类实现通读并听取了多个答案的建议后,我决定使用一个 .h 文件和 2 个不同的 .cpp 文件来实现这一点。我尝试使用此常见问题解答作为 guideline 来实现一个小型测试用例。代码如下:

test.h

#ifndef TEST_H
#define TEST_H

#include <iostream>
#include <cmath>
#include <complex>

template<typename T> 
class test{
public:
static bool IsClose(const T &a,const T &b);
};
#endif

testImpl.h

#include "test.h"

template <typename T> 
bool test<T>::IsClose(const T &a,const T &b){
    return (std::abs(a-b) <= (1e-8 + 1e-5 * std::abs(b)));
}

testImpl.cpp

#include "testImpl.h"

template class test<int>;
template class test<double>;

ma​​in.cpp

#include "test.h"
#include <iomanip>
int main(){
    std::cout << std::boolalpha << test<double>::IsClose(1e-7,1.1e-7) << std::endl;
    return 0;
}

使用 g++ -o test main.cpp testImpl.cpp 编译时出现以下错误

main.cpp: In function ‘int main()’:
main.cpp:4:36: error: ‘test’ is not a template
     std::cout << std::boolalpha << test<double>::IsClose(1e-7,1.1e-7) << std::endl;

如果有人能告诉我我哪里出错了,您的帮助将不胜感激。提前致谢!!此外,如果有更好的方法来实现我正在尝试做的事情,也欢迎您对此提出想法。

解决方法

我终于明白了。我需要让编译器知道它需要使用更新版本的 C++。所以, g++ -std=c++17 -o test main.cpp testImpl.cpp 很好地为我编译了代码。

仅当您使用 gcc 7.5.0 版时才需要使用 -std 标志。之后的所有 gcc 版本都使用 g++ -o test main.cpp testImpl.cpp

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。