【发布时间】:2013-12-20 20:56:31
【问题描述】:
我想在 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);
}
}
但是,头文件中的定义对我来说看起来很奇怪,所以我想将定义与声明分开,如下所示:
//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);
}
和:
//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);
}
有什么办法吗?
【问题讨论】:
-
看起来很奇怪并不是 IMO 的充分理由。没有办法做到这一点,不涉及一些妥协,所以我会习惯它。
-
您的模板定义需要保留在头文件中,但您可以在 class {} 块定义之外(仍然在 .h 文件中)以您的方式声明函数
-
代码甚至都无法编译...您只能在包含类的命名空间中编写特化。对于两者:GCC:
error: explicit specialization in non-namespace scope 'class myclass'。叮当声:error: explicit specialization of 'Trigger' in class scope。你在使用 MSVC 吗? -
我认为您将显式实例化和专业化混入同一个篮子。他们不一样。后者通常提供替代实现,前者提供将实例分配给特定翻译单元的机制。如果您想在指定特定编译单元的同时进行专业化,请参阅下面 Mike 的回答。
标签: c++ templates template-specialization member-functions