在库中展示ConstexPR专用模板功能

Exposing constexpr specialized template functions in a library

本文关键字:专用 功能 ConstexPR      更新时间:2023-10-16

我有一个带有模板函数的类。其中之一是A 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>。当我使用nm检查libmyClass.so时,我可以看到使用另一个Class2创建的MyFNC2模板,但MyFNC1不是。我知道这是原因,但是无论如何是否有任何使代码工作的方法?

我正在使用G 版本4.4.2。

如果我更改:

template std::string myclass::myfnc2<AnotherClass2>() {return "str2"; }

to

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