1
我有一个类模板,调用C库中的外部函数。根据专业化(主要是float
和double
)它应该调用不同的功能。我可以通过模板专业化来实现这一点。模板专精与静态constexpr成员(函数指针)
// -*- compile-command: "g++ -Wall -Wextra -Werror -pedantic -std=c++14 main.cpp -lm && ./a.out" -*-
#include <iostream>
extern "C" { // for illustration: not using cmath, but linking against libm
float sinf(float);
double sin(double);
}
template <typename T> struct Sin_callback;
template <> struct Sin_callback<float> { static constexpr auto sin_cb = sinf; };
template <> struct Sin_callback<double> { static constexpr auto sin_cb = sin; };
template <typename T> class Sin{
static constexpr Sin_callback<T> m_cb {};
T m_arg;
public:
Sin(T&& arg): m_arg(arg) {}
T calc() { return m_cb.sin_cb(m_arg); }
};
int main(){
Sin<double> dbl(1.0);
Sin<float> flt(1.0);
std::cout.precision(17);
std::cout << "ref:\t0.84147098480789650665" << std::endl;
std::cout << "double:\t" << dbl.calc() << std::endl;
std::cout << "float:\t" << flt.calc() << std::endl;
return 0;
}
输出使用gcc 5.4时:
ref: 0.84147098480789650665
double: 0.8414709848078965
float: 0.84147095680236816
但如果我尝试编译此使用铛(包括3.8和4.0)编译失败:
/tmp/main-75afd0.o: In function `Sin<double>::calc()':
main.cpp:(.text._ZN3SinIdE4calcEv[_ZN3SinIdE4calcEv]+0x14): undefined reference to `Sin_callback<double>::sin_cb'
/tmp/main-75afd0.o: In function `Sin<float>::calc()':
main.cpp:(.text._ZN3SinIfE4calcEv[_ZN3SinIfE4calcEv]+0x14): undefined reference to `Sin_callback<float>::sin_cb'
clang-4.0: error: linker command failed with exit code 1 (use -v to see invocation)
下面的代码用gcc编译
我不明白为什么专业化没有实例化。有任何想法吗?
非常感谢!变量模板有很大的帮助,因为我的实际回调函数有大量的参数(函数来自lapack)。只是好奇:你知道我的原始代码是否符合标准(即这是一个“clang”错误)或“未定义”的行为(在这种情况下,我希望''gcc''来警告我)? –