c++ - 模板类,函数特化

标签 c++ templates

我想要一个类似于下面的模板类。然后,我希望其中有一个函数,该函数具有依赖于 CLASS 模板参数的模板特化。我如何使这项工作?我意识到我提供的代码在很多层面上都是错误的,但这只是为了说明这个概念。

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>) { .. }
};

关于c++ - 模板类,函数特化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2349995/

相关文章:

c++ - 与函数指针转换相关的 lambda 对象的生命周期

区分枚举类和常规枚举的 C++11 类型特征

c++ - 执行 POST 请求时服务器的响应字符串不完整

templates - 如何在flask jinja2模板中加密id

c++ - 模板友元

c++ - 为什么结构必须与模板类在同一个命名空间中才能编译?

c++ - Boost 线程在作业完成之前就终止了

c++ - 无参数情况下的参数转发

javascript - jQuery addClass() 在某些媒体查询中不起作用

c++ - 如何使用 'using' 声明模板基类的模板方法?