Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/templates/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 模板中右值引用和常量左值引用之间的重载_C++_Templates_C++11_Rvalue Reference - Fatal编程技术网

C++ 模板中右值引用和常量左值引用之间的重载

C++ 模板中右值引用和常量左值引用之间的重载,c++,templates,c++11,rvalue-reference,C++,Templates,C++11,Rvalue Reference,我想根据参数是否为临时对象来重载两个函数,因此我编写如下代码: #include <iostream> void f(int &&) { std::cout << "&&" << std::endl; } void f(const int&) { std::cout << "const &" << std::endl; } int main() { int i; f(

我想根据参数是否为临时对象来重载两个函数,因此我编写如下代码:

#include <iostream>

void f(int &&)
{
  std::cout << "&&" << std::endl;
}

void f(const int&)
{
  std::cout << "const &" << std::endl;
}

int main()
{
  int i;
  f(i);
  f(i + 1);
}
#include <iostream>

template <typename T>
void f(T &&)
{
  std::cout << "&&" << std::endl;
}

template <typename T>
void f(const T&)
{
  std::cout << "const &" << std::endl;
}

int main()
{
  int i;
  f(i);
  f(i + 1);
}
但是,当我将代码更改为使用以下模板时:

#include <iostream>

void f(int &&)
{
  std::cout << "&&" << std::endl;
}

void f(const int&)
{
  std::cout << "const &" << std::endl;
}

int main()
{
  int i;
  f(i);
  f(i + 1);
}
#include <iostream>

template <typename T>
void f(T &&)
{
  std::cout << "&&" << std::endl;
}

template <typename T>
void f(const T&)
{
  std::cout << "const &" << std::endl;
}

int main()
{
  int i;
  f(i);
  f(i + 1);
}
有什么问题吗?使用模板时,如何优化可移动临时对象

编辑:

<>实际上,这是我读C++底漆时的测试代码。它说:

template <typename T> void f(T&&);       // binds to nonconst rvalues
template <typename T> void f(const T&);  // lvalues and const rvalues
template void f(T&&);//绑定到非右值
模板void f(常数T&);//左值和常值
经过我的实验,这本书似乎在这里出错了

template <typename T>
void f(T &&)
{
  std::cout << "&&" << std::endl;
}

您所说的“使用模板时如何优化可移动临时对象”是什么意思
T&&
本身是最佳的,因为它绑定到所有内容,并允许您恢复用作argument@PiotrS. 例如,如果它将变量i绑定到const T&,并将表达式i+1绑定到T&&,那么我可以从i+1生成的临时项目中移动资源。这就是为什么会有一个条件移动,即
std::forward
,这取决于为
T
推导的类型,它要么移动,要么根本不移动。对于右值,不必显式使用
std::move
。请注意,
T&
其中
T
是一个类型模板参数,它是一个转发引用,其行为不同于常规的右值reference@PiotrS. 当我对函数参数使用右值引用时,我希望这个参数总是绑定到临时对象。但是在这种情况下,它也绑定到变量。
T&
如果
T
是一个类型模板参数,则它是一个转发引用,而不是一个右值引用,太阳下的一切都可以被转发引用td::decay,std::forward,。。。在我理解这种行为之前,我似乎还需要学习更多-_-||
template <typename T>
struct helper
{

    void f(T &&)
    {
      std::cout << "&&" << std::endl;
    }

    void f(const T&)
    {
      std::cout << "const &" << std::endl;
    }

};

template <typename T>
void f(T &&t)
{
     helper<typename std::decay<T>::type>().f(std::forward<T>(t));
}