【发布时间】:2019-01-08 21:08:46
【问题描述】:
我正在开发一个 C++ 库,我需要在其中向用户提供类模板。
这个类的模板参数是一个引用。但是,我收到链接器错误。这是一个最小的测试用例:
test.hh
#ifndef TEST_HH_
#define TEST_HH_
template <double const& val>
struct A{};
constexpr double zero = 0.;
A<zero> foo();
#endif // TEST_HH_
test.cpp
#include "test.hh"
A<zero> foo(){ return A<zero>(); }
main.cpp
#include "test.hh"
int main()
{
foo();
}
编译这段代码时,我收到警告:
'A<zero> foo()' used but never defined
随后出现链接器错误:
undefined reference to foo()
我试图用 int 替换双精度:
template <int val>
struct A{};
它链接了(当传递 int 作为参数 ofc 时),但我真的需要一个 double。
当模板类涉及链接错误时,我也尝试了一个常见的解决方案,我在test.hh 中实现了foo() 函数而不是test.cpp,但我想避免只将所有代码放在标题中。
【问题讨论】:
标签: c++ templates linker c++14 non-type