【问题标题】:How can I specify non-deducible template parameters on a constructor? [duplicate]如何在构造函数上指定不可演绎的模板参数? [复制]
【发布时间】:2015-10-01 16:25:13
【问题描述】:

可以给一个模板化的构造函数提供无法推导的模板参数:

struct X
{
    int i;

    template<int N>
    X() : i(N)
    {
    }
};

你会如何使用这样的构造函数?能用吗?

【问题讨论】:

  • 你不能。由于构造函数没有名称,因此您不能指定构造函数模板的模板参数。所有模板参数都必须是可推导的。
  • 当然可以通过其他方式实现编译时常量表达式初始化,例如带有std::integral_constant 参数等的标签调度
  • 你的用例是什么?
  • @DieterLücking,我会用一个类型来包装对象的分配。我正在使用一个函数,类似于make_unique。

标签: c++ templates


【解决方案1】:

不,你can't specify constructor template arguments。有几种选择。

  1. 正如@KerrekSB 在 cmets 中指出的那样,您可以给构造函数模板一个 std::integral_constant 参数,当作为参数传递时,将推导出 N:

代码:

#include <cassert>
#include <type_traits>

struct X
{
    int i;

    template<int N>
    X(std::integral_constant<int, N>) : i(N)
    {
    }
};

int main()
{
    std::integral_constant<int, 6> six;
    X x(six);
    assert(x.i == 6);
}

Live Example

  1. 您可以编写一个专用的 make_X&lt;N&gt; 模板包装器来隐藏 integral_constant 样板:

代码:

template<int N>
X make_X()
{
    return X(std::integral_constant<int, N>{});        
}

int main()
{
    auto y = make_X<42>();
    assert(y.i == 42);
}

Live Example

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-09-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-19
    • 2011-02-21
    • 2021-09-25
    • 2015-05-05
    相关资源
    最近更新 更多