【问题标题】:Capture the variadic template types?捕获可变参数模板类型?
【发布时间】:2014-05-22 17:53:48
【问题描述】:

例如,我有如下代码

template<class... Ts>
void f(Ts... args)
{
}

当传递以下参数时

int j = 5;
int& i = j;
f(i);

void g(int& i)
{
    f(i);
}

在上述两种情况下,捕获的类型都是 int 而不是 int&。如何让它捕获与 i 相同类型的 int&?谢谢。

【问题讨论】:

    标签: c++ templates c++11 variadic-templates


    【解决方案1】:

    类型模板参数推导去除了 cv-qualifiers 和 ref-qualifers(它还将数组类型转换为指针类型,将函数类型转换为函数指针类型。)

    如果您希望引用成为推导类型的一部分,请将其添加到声明符中。 (const 也是如此。)

    template<class... Ts>
    void f(Ts&... args);
    

    如果您希望根据参数是左值还是右值,推导出的类型是左值引用还是右值引用,请使用“通用引用”。

    template<class... Ts>
    void f(Ts&&... args);
    

    (尽管后者看起来像,它确实不是意味着“仅接受右值”。这种情况要少得多。对于这种情况,请参阅How to make template rvalue reference parameter ONLY bind to rvalue reference?

    注意:只有当传入的变量被声明为引用时,才没有方法可以使函数通过引用获取其参数。这是因为引用的行为总是与它所引用的对象完全相同(除非应用了decltype)。

    【讨论】:

    • 我有一个类似的问题......如果函数被称为template&lt;class... Ts&gt; void f(int x, Ts&amp;&amp;... args) 怎么办? args 中传递的参数是否仍然是左值或右值引用,还是只有右值引用?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-06-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多