std::绑定可变参数模板成员函数和通用引用
std::bind with variadic template member function and universal references
在这里我有一小段代码,它可以编译和工作得很好 (至少在我的 GCC 7.3.0 和 Ubuntu 18.04 中(:
#include <functional>
#include <string>
#include <iostream>
void func(int a, const std::string& b, const std::string& c)
{
std::cout << a << b << c << std::endl;
}
class Test
{
public:
template <typename ... ARGS>
bool func_to_bind(ARGS&& ... args) const {
func(args...);
return true;
}
template <typename ... ARGS>
void binding_func(ARGS&& ... args) const
{
auto func_obj = std::bind(&Test::func_to_bind<int&, ARGS&...>, this, 42, args...);
func_obj();
}
};
int main()
{
Test obj;
obj.binding_func(std::string("one"), std::string("two"));
}
我不明白的部分是这一行:
std::bind(&Test::func_to_bind<int&, ARGS&...>, this, 42, args...);
为什么编译器需要使用引用作为模板类型参数? 如果我像这样从 int 中删除引用:
std::bind(&Test::func_to_bind<int, ARGS&...>, this, 42, args...);
它不会编译。另外,如果我func_to_bind签名更改为:
bool func_to_bind(ARGS& ... args) const
即使缺少引用,它也可以很好地编译。 谁能解释一下这里到底发生了什么? 我也做了一些搜索,发现了这个问题: 如何结合std::bind((,可变参数模板和完美的转发?
但我不完全明白答案。
如果显式指定模板参数int
,则func_to_bind
的参数类型将变为int&&
,即右值引用类型。请注意,存储的参数通过std::bind
作为左值s 传递给可调用对象:
否则,普通存储的参数 arg 将作为左值参数传递给可调用对象:
左值不能绑定到右值引用参数,则调用失败。
如果显式指定模板参数int&
,则func_to_bind
的参数类型将变为int&
,即左值引用类型;左值可以绑定到左值引用,然后它工作正常。
如果您将func_to_bind
的参数类型更改为ARGS&
,它将始终是一个左值引用,出于上述相同原因,它将正常工作。
相关文章:
- 区分接受常量参数的函数引用/指针和与函数参数同名的非常量参数
- 类 Referention 中C++回调函数引用非静态函数
- 使用函数引用指向节点的指针删除链表中的节点?
- 解释通过从函数引用返回数组的语法
- "Class1"类"Class2"对象作为私有数据成员。如何通过"Class 2"函数引用"Class1"对象?
- 使用默认构造函数引用成员变量初始化错误
- 无法调用函数引用 c++
- 使用 decltype(this) 获取函数引用
- 我应该如何定义返回指针的函数?(引用指针与指针指针)
- 从内联函数引用文件静态变量
- Boost::将sigaction函数引用绑定到实例
- 一种比函数引用更有效的方法
- 奇怪的未定义函数引用,函数调用C++不存在
- 是否可以检测绑定成员函数引用的对象是否被删除或销毁
- 构造函数引用参数导致seg错误
- 是否可以使函数模板从函数引用中获取“decltype”
- 无法让 Lua 函数引用"self"
- 如何解析变量和函数引用(Linker & Compiler)?
- 从不同模块调用函数 - 引用错误
- 如何在主函数中连接到数据库,然后从其他函数引用它