首页 > 解决方案 > 在库中公开 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。

标签: c++c++11templatesg++

解决方案


如果我改变:

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.


推荐阅读