如何根据模板参数选择替代成员函数实现? [英] How do I select an alternative member function implementation, depending on a template argument?

查看:103
本文介绍了如何根据模板参数选择替代成员函数实现?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有这个类:

template</*some other parameters here */class toggle>
class Foo
{
   void function();
   //Lots of other non-parametrized member functions
}

如果toggle是某种特定类型,我想要函数使用一个替代实现,而对于所有其他情况,我希望它使用标准实现。这应该完全在编译时完成,因为类的外部用户应该能够实例化这个模板(有意地,为了节省内存和一点性能)缺乏一些功能。

Now, if toggle is of some certain type, I want function to use an alternative implementation, and for all other cases I want it to use the standard implementation. This should be done completely at compile time, since outside users of the class should be able to instantiate this template that (intentionally, in order to save memory and a little performance) lacks some functionality.

catch:简单的专门化整个类是不现实的,因为Foo将有很多其他方法,不依赖于这个切换,这也将有

The catch: Simply specializing the whole class is not realistic, since Foo will have a lot of other methods which don't depend on this toggle, which would also have to be implemented again, making everything a huge waste of space.

推荐答案

我认为这是你要的:

#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

这篇关于如何根据模板参数选择替代成员函数实现?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆