我有一个包含模板函数的类。其中一个是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时,我可以看到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
。