C ++模板模板推断类型参数

Reg*_*lez 4 c++ templates

我有一个基本类型

template<int p> 
struct Base {};
Run Code Online (Sandbox Code Playgroud)

以及基于许多版本的Base构建的更复杂的内容(有些是int模板,有些是类模板):

template<template<auto inner> typename basetype, typename p, typename q>
struct Complex {};
Run Code Online (Sandbox Code Playgroud)

然后,我创建这样的变量:

Complex<Base, Base<1>, Base<2>> c;
Run Code Online (Sandbox Code Playgroud)

有没有办法来推断我的第一个模板参数Base,或pq专门的版本basetype,所以我可以写

Complex<Base<1>, Base<2>> c;
Run Code Online (Sandbox Code Playgroud)

我想没有。但是模板有时会隐藏一些魔术。

Bri*_*ian 9

如果要Complex始终让其两个参数成为同一模板的特化,则可以使用部分特化来实现:

// the primary template remains incomplete, so most uses of it will be an error
template <class T, class U> struct Complex;

template <template<auto> typename basetype, auto p_arg, auto q_arg>
struct Complex<basetype<p_arg>, basetype<q_arg>> {
    // ...
};
Run Code Online (Sandbox Code Playgroud)

当你实例化Complex<Base<1>, Base<2>>,参数basetypep_arg以及q_arg将推导出Base12分别。