模板类,函数专门化 [英] Template class, function specialization

查看:116
本文介绍了模板类,函数专门化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想要一个模板类,看起来像我下面的东西。然后,我想要一个函数与模板专门化取决于一个CLASS模板参数。如何使这项工作?我知道我提供的代码在许多层次上是错误的,但它只是为了说明这个概念。

I want to have a template class that looks something like what I have down below. Then, I want a function in it with a template specialization depending on a CLASS template parameter. How do I make this work? I realize the code I provided is wrong on many levels, but it's just to illustrate the concept.

template <typename _T, size_t num>
class Foo
{
    // If num == 1, I want to call this function...
    void Func<_T, 1>()
    {
        printf("Hi!");
    }

    // Otherwise, I want to call this version.
    void Func<_T, num>()
    {
        printf("Hello world!");
    }
};


推荐答案

struct Otherwise { };
template<size_t> struct C : Otherwise { };

// don't use _Uppercase - those names are reserved for the implementation
// (i removed the '_' char)
template <typename T, size_t num>
class Foo
{
public:
    void Func() { Func(C<num>()); }

private:
    // If num == 1, I want to call this function...
    void Func(C<1>)
    {
        printf("Hi 1!");
    }

    // If num == 2, I want to call this function...
    void Func(C<2>)
    {
        printf("Hi 2!");
    }

    // Otherwise, I want to call this version.
    void Func(Otherwise)
    {
        printf("Hello world!");
    }

    //// alternative otherwise solution:
    // template<size_t I>
    // void Func(C<I>) { .. }
};

这篇关于模板类,函数专门化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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