c++ - 在库中公开 constexpr 专用模板函数

标签 c++ c++11 templates g++

我有一个带有模板函数的类。其中之一是 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/

相关文章:

c++ - Objective-C++ 从 C++ 对象为 OBj-C 属性赋值

C++:调试 C++ 模板链接器错误

c++ - 我们可以有一个具有多种返回类型的函数吗? (C++11 及以上版本)

gcc - 使用 c++0x 在 g++ 上出现 strdup 错误

c++ - C++ vector 的 size() 和 capacity()

c++ - Boost.Test的数据测试用例真的需要C++11吗?

c++ - 如何避免 "dynamic initialization in unreachable code"警告?

c++ - 如何在编译时初始化一个 float 组?

我的类中的 c++ condition_variable wait_for 谓词,std::thread <unresolved overloaded function type> error

c++ - 析构函数可以是最终的吗?