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++ - 将复杂参数放入 min 函数时出错?为什么?(Eclipse C++)

c++ - 具有 x、y、z 的点和具有 x()、y()、z() 的点的模板函数

c++ - 如何设置 QFormLayout 第一列的最小宽度?

PHP 扩展 : Segmentation fault when returning from a function

c++ - Debug模式自发关闭?

c++ - 蒂姆·斯威尼在想什么? (这个 C++ 解析器是如何工作的?)

c++ - 仅用于基本 POD 的模板特化

c++ - 带有复制构造函数的 enable_if

c++ - C++中的字符串标记器

c++ - 是 std :vector<char[30]> valid, 还是如何实现的? (固定大小数组的 vector ?)