c++ - 在库中公开 constexpr 专用模板函数
问题描述
我有一个带有模板函数的类。其中之一是constexpr函数。我想将此类编译为库并使用其他客户端的专用模板函数。例子:
//in myclass.h
struct myclass{
template<typename Entity>
static constexpr const char* myfnc1();
template<typename Entity>
static std::string myfnc2();
};
//in myclass.cpp
template<> const char* myclass::myfnc1<AnotherClass>() {return "str";}
template<> std::string myclass::myfnc2<AnotherClass2>() {return "str2"; }
template const char* myclass::myfnc1<AnotherClass>();
template std::string myclass::myfnc2<AnotherClass2>();
当我尝试myfnc1<AnotherClass>
在另一个库中使用时,它说它没有定义,但我可以使用myfnc2<AnotherClass2>
. 当我检查 libmyclass.so 时,nm
我可以看到 myfnc2 模板是用 AnotherClass2 创建的,但 myfnc1 不是。我知道这是原因,但想知道是否有办法让代码正常工作?
我正在使用 g++ 版本 4.4.2。
解决方案
如果我改变:
template std::string myclass::myfnc2<AnotherClass2>() {return "str2"; }
至
template<> std::string myclass::myfnc2<AnotherClass2>() {return "str2"; }
我可以编译。错字?
> g++ -fPIC -shared x.cpp -O3 -o x.so
> nm x.so | c++filt | grep fnc
结果:
0000000000000680 T char const* myclass::myfnc1<AnotherClass>()
0000000000000690 T std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > myclass::myfnc2<AnotherClass2>()
我不知道您是否真的能够在代码失败的情况下进行编译。但是我可以通过更改对其进行编译并获得预期的结果。但我使用的是g++ (GCC) 8.2.1
.
推荐阅读
- c# - 在 C# 8.0 中有没有办法在类上公开默认成员实现?
- php - 使用函数中包含的函数和变量
- angular - 角度应用程序不适用于 Edge
- wordpress - 我应该在 WordPress 中插入哪些“附加 CSS”以将默认字体设置为 Proxima Nova?
- mongodb - 为什么我不能取消屏蔽 mongod.service?
- postgresql - 如何将 GeoJSON 多面体插入 PostGIS 表?
- r - 在多行 R 中具有匹配 ID 的条件或过滤参数
- backup - AS400 将整个系统保存在 SAVF 中
- emacs - Cx 4 b 在当前缓冲区的左边打开一个新缓冲区
- azure - PersonID 计算(Azure 人脸 API)