假设我有这个类:
template</*some other parameters here */class toggle>
class Foo
{
void function();
//Lots of other non-parametrized member functions
}
现在,如果切换是某种特定类型,我希望函数使用替代实现,而对于所有其他情况,我希望它使用标准实现。这应该在编译时完全完成,因为类的外部用户应该能够实例化这个模板(有意地,为了节省内存和一点性能)缺少一些功能。
要点:简单地特化整个类是不现实的,因为 Foo 会有很多不依赖于这个切换的其他方法,这些方法也必须再次实现,这使得一切都成为空间的巨大浪费。
最佳答案
我认为这就是您的要求:
#include <iostream>
#include <string>
template <class toggle>
class Foo
{
public:
void function() { std::cout << "Default\n"; }
};
template <>
void Foo<int>::function() { std::cout << "int\n"; }
int main ()
{
Foo<std::string>().function();
Foo<int>().function();
return 0;
}
输出:
Default
int
关于c++ - 如何根据模板参数选择替代成员函数实现?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9503042/