【问题标题】:Class with two or more template overloads具有两个或多个模板重载的类
【发布时间】:2022-01-01 09:58:48
【问题描述】:

假设我有一个我想用两个“重载”声明的类,一个接受 1 个模板参数,另一个接受 2 个,如下面的伪代码:

template <typename I>
class B {
public:
};


template <typename F, typename I>
class B { 
};

这样B 只能用 1 或 2 个参数实例化:

B<int> hello;
B<int, int> hello2;

这样做的正确方法是什么?

【问题讨论】:

  • template &lt;typename A, typename B = void&gt;(或其他占位符而不是void),然后部分专门用于B == void

标签: c++ templates overloading


【解决方案1】:

简单回答:

template <typename A, typename... Args> // ellipsis makes Args a
class B                                 // template parameter pack
{
public:
};

int main()
{
    B<int> hello;
    B<int, int> hello2;
    B<int, int, double> hello3;
}

现在Args 被称为模板参数包

更具体到你想要的:

template <typename F, typename I = int>
class B
{
public:
};

int main()
{
    B<int> hello;
    B<int, int> hello2;
}

这个最多允许两个模板参数。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-20
    • 1970-01-01
    • 2016-11-29
    • 2015-11-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多