c++ - 涉及模板参数解决方法的模板参数

标签 c++ templates specialization

我有以下部分专业:

constexpr int NUM_ARGS = 3;

template <typename, typename, int> struct Dispatcher;

template <typename T, typename V>
struct Dispatcher<T, V, NUM_ARGS-1> {};

但现在我需要 NUM_ARGS 本身作为 Dispatcher 中的模板参数。但是

template <typename, typename, int, int> struct Dispatcher;

template <typename T, typename V, int NUM_ARGS>
struct Dispatcher<T, V, NUM_ARGS, NUM_ARGS-1> { ...

是非法的。那么解决这个问题的方法是什么?

对于 Pradhan 的解决方案,这种非法特化的解决方法是什么?

template <int M, int N, typename... Args> struct Test;

template <int M, typename... Args>
struct Test<M, M-1, Args...> {};

甚至不允许使用默认模板参数?

最佳答案

虽然您不能在特化参数中对模板参数进行算术运算,但您可以在类型参数中进行运算。用一个比问题中的例子更简单的例子来说明:

template <int M, int N, typename Specialization = void>
class Test
{
    public:
    void foo(){cout << "Primary template." << endl;}
};

template <int M, int N>
class Test<M, N, enable_if_t<N==M-1>>
{
    public:
    void foo(){cout << "Specialization." << endl;}
};

int main()
{
    Test<5,10>().foo();
    Test<5,4>().foo();
    return 0;
}

输出:

Primary template.
Specialization.

编辑:为了允许可变参数,我们必须将 Specialization 保留为没有默认值的类型参数,并使用模板别名使界面更简洁。

template <int M, int N, typename Specialization, typename... Rest>
class Test
{
    static_assert(std::is_same<Specialization, void>::value, "Don't use Test directly. Use TestHelper instead.");
    public:
    void foo(){cout << "Primary template." << endl;}
};

template <int M, int N, typename... Rest>
class Test<M, N, enable_if_t<N==M-1>, Rest...>
{
    public:
    void foo(){cout << "Specialization." << endl;}
};

template <int M, int N, typename... Rest>
using TestHelper = Test<M, N, void, Rest...>;

int main()
{
    TestHelper<5,10, int, double, char>().foo();
    TestHelper<5,4, int, double, char>().foo();
    return 0;
}

Coliru Demo .

关于c++ - 涉及模板参数解决方法的模板参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29216020/

相关文章:

c++ - 从重心到笛卡尔

C++ 数组与 vector

java - 从 JavaScript 访问列表项

c++类模板特化,无需重新实现一切

c++ - 无法连接到 SMTP 服务器

c++ - 从标准输入捕获字符,无需等待按下 Enter 键

c++ - 如何在 C++ 中强制使用奇怪的重复模板模式

c++ - (void) sizeof (0[array]) 是什么意思?

c++ - 部分特化可变参数模板类型名为 void

成员函数的 C++ 模板特化