std::绑定可变参数模板成员函数和通用引用

std::bind with variadic template member function and universal references

本文关键字:函数 引用 成员 绑定 变参 参数 std      更新时间:2023-10-16

在这里我有一小段代码,它可以编译和工作得很好 (至少在我的 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&,它将始终是一个左值引用,出于上述相同原因,它将正常工作。