假设我在 Visual Studio 中有以下代码
class foo
{
public:
template<typename t>
void foo_temp(int a , t s_)
{
std::cout << "This is general tmeplate method";
}
template<>
static void foo_temp(int a , int s)
{
std::cout << "This is a specialized method";
}
};
int main()
{
foo f;
f.foo_temp<std::string>(12,"string");
}
现在我试图将其转换为 GCC。通过关于 SO 的其他问题,我注意到如果类不是专门的,则在 GCC 成员方法中不能专门化。因此我想出了这个解决方案
class foo
{
public:
template<typename t>
void foo_temp(int a , t s_)
{
std::cout << "This is general template method";
}
};
template <>
/*static*/ void foo::foo_temp<int>(int a, int value) {
std::cout << "Hello world";
}
现在这似乎可以解决问题,但是当我将 static 关键字包含到语句中时,我得到了错误
explicit template specialization cannot have a storage class
现在 这个 线程谈论它,但我仍然对如何在这里应用它感到困惑。关于如何使最后一个方法成为静态的任何建议?另外我仍然对为什么模板化方法在 GCC 中不能是静态的感到困惑?
这是视觉工作室代码
class foo
{
public:
template<typename t>
void foo_temp(int a , t s_)
{
std::cout << "This is general tmeplate method";
}
template<>
static void foo_temp(int a , int s)
{
std::cout << "This is a specialized method";
}
};
int main()
{
foo f;
f.foo_temp<std::string>(12,"string");
}
原文由 James Franco 发布,翻译遵循 CC BY-SA 4.0 许可协议
你不能;语言不支持它。
他们能;它们不能既是静态的又是非静态的。例子:
我很困惑为什么你必须有一个(非静态)模板成员函数的静态特化。我会认真地重新评估这段代码的完整性。
请注意,对于评论中的问题,不可能对静态成员函数进行模板特化,因为在这种情况下根本不可能对成员函数进行模板特化。 (改用重载。)