我有一个带有模板函数的类。其中之一是 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 时我可以看到使用 AnotherClass2 创建的 myfnc2 模板,但 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++ - 在库中公开 constexpr 专用模板函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54946789/