如何根据模板参数选择替代成员函数实现
How do I select an alternative member function implementation, depending on a template argument?
假设我有这个类:
template</*some other parameters here */class toggle>
class Foo
{
void function();
//Lots of other non-parametrized member functions
}
现在,如果toggle是某种特定类型的,我希望函数使用替代实现,对于所有其他情况,我希望它使用标准实现。这应该完全在编译时完成,因为类的外部用户应该能够实例化这个模板,而这个模板(为了节省内存和一点性能)缺乏一些功能。
问题是:简单地专门化整个类是不现实的,因为Foo将有很多其他方法不依赖于这种切换,而这种切换也必须再次实现,这使得一切都是巨大的空间浪费。
我想这就是你想要的:
#include <iostream>
#include <string>
template <class toggle>
class Foo
{
public:
void function() { std::cout << "Defaultn"; }
};
template <>
void Foo<int>::function() { std::cout << "intn"; }
int main ()
{
Foo<std::string>().function();
Foo<int>().function();
return 0;
}
输出:
Default
int
您可以专门化基类:
template<class toggle>
class FooFunction {
public:
void function();
};
template<>
class FooFunction<blah> {
public:
void function();
};
template<class toggle>
class Foo : public FooFunction<toggle> {
//Lots of other non-parametrized member functions
};
如果使function
成为一组重载的函数模板对您来说是可以接受的,那么:
// toggle is not a dependent type so we solve that
template<
typename T = toggle
, typename = typename std::enable_if<
std::is_same<T, int>::value
>::type
>
void function()
{ /* implementation for int */ }
template<
typename T = toggle
, typename = typename std::enable_if<
!std::is_same<T, int>::value
>::type
// dummy parameter to make this declaration distinct from the previous one
typename = void
>
void function()
{ /* implementation for others */ }
这是用C++11风格编写的,但可以使用C++03。(在某些情况下,这可能取决于SFINAE在某种程度上是C++03的灰色区域,但我对规则了解不够。)
模板专业化,尝试调试它,并注意并非所有功能都需要专业化:
template <class T> class Spec
{
public:
void Func()
{
}
void Func2()
{
}
};
void Spec<double>::Func()
{
}
int main( int argc, char *argv )
{
Spec<int> spec1;
spec1.Func();
spec1.Func2();
Spec<double> spec2;
spec2.Func();
spec2.Func2();
return 0;
}
相关文章:
- 对RValue对象调用的LValue ref限定成员函数
- 为什么使用 "this" 指针调用派生成员函数?
- 将公共但非静态的成员函数与ALGLIB集成
- 使用指向成员的指针将成员函数作为参数传递
- 将重载的成员函数传递给函数模板
- 我不小心调用了一个没有自己类对象的成员函数.但这是怎么回事呢
- 如何在C++中使用非静态成员函数作为回调函数
- C++错误C2600:无法定义编译器生成的特殊成员函数(必须首先在类中声明)
- 关联容器的下界复杂性:成员函数与非成员函数
- 在 C++ 中用派生类型重写成员函数
- 链表的泛型函数remove()与成员函数remove)
- 如何将lambda作为模板类的成员函数参数
- constexpr构造函数需要常量成员函数时出现问题
- 将自由函数绑定为类成员函数
- 区分非成员函数和头文件中的成员函数
- 如何从子成员函数修改父公共成员变量
- 保留对其他类的成员函数的引用
- 在运算符重载定义中使用成员函数(const错误)
- 内联如何影响模块接口中的成员函数
- 将成员函数指针作为参数传递给模板方法