首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >C++03中的完美转发

C++03中的完美转发
EN

Stack Overflow用户
提问于 2010-08-29 02:00:23
回答 2查看 5.1K关注 0票数 25

如果你有这个功能

代码语言:javascript
复制
template<typename T> f(T&);

然后试着用下面这样的rvalue来调用它

代码语言:javascript
复制
f(1);

为什么T不能被推导为const int,使参数成为const int&,从而可以绑定到rvalue?

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2010-08-29 02:22:23

这是在recent C++0x forwarding question中链接的the document中提到的一个潜在解决方案。

它将工作得相当好,但它破坏了现有的代码。考虑一下(直接从文档中):

代码语言:javascript
复制
template<class A1> void f(A1 & a1)
{
    std::cout << 1 << std::endl;
}

void f(long const &)
{
    std::cout << 2 << std::endl;
}

int main()
{
    f(5);              // prints 2 under the current rules, 1 after the change
    int const n(5);
    f(n);              // 1 in both cases
}

代码语言:javascript
复制
// helper function in a header

template<class T> void something(T & t) // #1
{
    t.something();
}

// source

#include <vector>

void something(bool) // #2
{
}

int main()
{
    std::vector<bool> v(5);

    // resolves to #2 under the current rules, #1 after the change
    something(v[0]);
}

这也无法转发值类别(左值或右值),这在C++03中不是什么大问题。但由于此修复只能在C++0x期间完成,因此在转发时,我们实际上会将自己排除在右值引用之外(这是一件坏事)。我们应该争取一个更好的解决方案。

票数 26
EN

Stack Overflow用户

发布于 2010-08-29 02:10:13

确实如此,但前提是您必须声明fT const &作为参数。

代码语言:javascript
复制
template <typename T> void f(T &);
template <typename T> void g(T const &);

void x() { f(1); }  // error: invalid initialization of non-const reference
void y() { g(1); }  // no error

如果同时声明f(T &)f(T const &),它将选择const限定的参数:

代码语言:javascript
复制
template <typename T> void f(T &);
template <typename T> void f(T const &);

void x() { f(1); } // no error, calls f(T const &)

现在,您可能会问“在第一个示例中,当它本可以生成类型为const int的临时类型并编译代码时,为什么要为对f的调用生成类型为int的临时类型?”我给你的最好答案是,当参数不是整数常量时,这将与重载解析行为不一致。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/3591832

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档