Iba*_*ban 6 c++ templates member-functions template-specialization
我想在cpp文件中定义模板函数的显式特化.那可能吗?更具体一点,我有以下代码,编译没有错误:
//class.h
class myclass
{
public:
/* Constructor */
myclass();
/* Trigger fcn */
template<typename T> T Trigger(T rn);
private:
/* Specializations of the templated Trigger(...) function */
template<> int Trigger<int>(int rn)
{
int_do(rn);
}
template<> double Trigger<double>(double rn)
{
double_do(rn);
}
}
Run Code Online (Sandbox Code Playgroud)
但是,我在头文件中的定义对我来说看起来很奇怪,所以我想将定义与声明分开,如下所示:
//class.h
class myclass
{
public:
/* Constructor */
myclass();
/* Trigger fcn */
template<typename T> T Trigger(T rn);
private:
/* Specializations of the templated Trigger(...) function */
template<> int Trigger<int>(int rn);
template<> double Trigger<double>(double rn);
}
Run Code Online (Sandbox Code Playgroud)
和:
//class.cpp
/* Specializations of the templated Trigger(...) function */
template<> int myclass::Trigger<int>(int rn)
{
int_do(rn);
}
template<> double myclass::Trigger<double>(double rn)
{
double_do(rn);
}
Run Code Online (Sandbox Code Playgroud)
有什么办法吗?
Mik*_*our 10
您唯一的错误是声明类中的特化.在标题中声明它们,但在类之外:
class myclass
{
public:
myclass();
template<typename T> T Trigger(T rn);
};
/* Specializations of the templated Trigger(...) function */
template<> int myclass::Trigger<int>(int rn);
template<> double myclass::Trigger<double>(double rn);
Run Code Online (Sandbox Code Playgroud)
然后你可以在源文件中定义它们,就像你一样.
请注意,您的第一个代码段不会编译(除非您的编译器具有非标准扩展名),因为无法在类中声明特化.