完美转发在C ++ 03 [英] Perfect Forwarding in C++03

查看:111
本文介绍了完美转发在C ++ 03的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果您有此功能

template<typename T> f(T&);

然后尝试使用

f(1);

为什么T不能被推导为const int,因此可以绑定到右值?

Why isn't T just be deduced to be const int, making the argument a const int& and thus bindable to an rvalue?

推荐答案

这被提及为一个潜在的解决方案我在最近的C ++ 0x转发问题

This is mentioned as a potential solution in the document I linked in the recent C++0x forwarding question.

但它打破了现有代码。考虑(直接从文档):

It would work fairly well, but it breaks existing code. Consider (straight from the document):

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
}

// 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]);
}

这也无法转发值类别(lvalue或rvalue)在C ++ 03中的很多问题。但是由于这个修复只能在C ++ 0x期间完成,我们在转发(坏事)时会有效地关闭自己的值。我们应该努力寻求更好的解决方案。

This also fails to forward the value category (lvalue or rvalue), which isn't much of a problem in C++03. But since this fix could only be done during C++0x, we'd effectively shutting ourselves out from rvalue references when forwarding (a bad thing). We should strive for a better solution.

这篇关于完美转发在C ++ 03的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆