什么是“Hello,World!”。 “std :: ref”的示例 [英] What would be a "Hello, World!" example for "std::ref"?

查看:229
本文介绍了什么是“Hello,World!”。 “std :: ref”的示例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人可以给出一个简单的例子来演示 std :: ref 的功能吗?我的意思是一个例子,其中一些其他的结构(像元组或数据类型模板)只有使用它是不可能解释 std :: ref

Can somebody give a simple example which demonstrates the functionality of std::ref? I mean an example in which some other constructs (like tuples, or data type templates) are used only if it is impossible to explain std::ref without them.

我发现了两个关于 std :: ref 在这里这里。但是在第一个例子中,它涉及编译器中的一个错误,第二个例子使用 std :: ref 不包含 std :: ref ,它们涉及元组和数据类型模板,这些模板使理解这些示例很复杂。

I found two questions about std::ref here and here. But in the first one it goes about a bug in a compiler and in the second one, examples of use of std::ref do not contain std::ref and they involve tuples and data type templates which make understanding of these examples complex.

推荐答案

您应该考虑使用 std :: ref 当函数按值接受模板参数时,例如 std :: bind

You should think of using std::ref when a function takes a template parameter by value, such as std::bind.

std :: ref

std::ref is a value type that behaves like a reference.

这个例子可以证明使用 std :: ref

This example makes demonstrable use of std::ref.

#include <iostream>
#include <functional>

void increment( int &x )
{
  ++x;
}

int main()
{
  int i = 0;

  // Here, we bind increment to (a copy of) i...
  std::bind( increment, i ) ();
  //                        ^^ (...and invoke the resulting function object)

  // i is still 0
  std::cout << i << std::endl;

  // Now, we bind increment to std::ref(i)
  std::bind( increment, std::ref(i) ) ();

  // i has now been incremented.
  std::cout << i << std::endl;
}

输出:

0
1

这篇关于什么是“Hello,World!”。 “std :: ref”的示例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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