auto 推导的那个类型是什么?

what's that type deduced by auto?

在极少数情况下,我会想要显式声明变量?

那么 f4 的类型是什么?

以下代码来自cppreference

#include <random>
#include <iostream>
#include <memory>
#include <functional>

struct Foo {
    int data = 10;
};

int main()
{
    using namespace std::placeholders;  // for _1, _2, _3...

    Foo foo;  
    auto f4 = std::bind(&Foo::data, _1);  // bind to member data
    std::cout << f4(foo) << '\n';
}

ps1:我想声明一个绑定到 C::m1、C::m2...

的 std::bind 数组
class C
{
  string m1;
  string m2;
};

ps2: decltype解决了我的问题,谢谢大家。

typedef decltype(std::bind(&C::m1, placeholders::_1)) Field;
Field foo[] = 
{
  std::bind(&C::m1, placeholders::_1);
  std::bind(&C::m2, placeholders::_1);
}

f4 的类型将是一些未指定的类型,从 std::bind 返回。 您可以在编译器错误中查看它,例如使用 TD.

template<typename>
struct TD;

// in main
TD<decltype(f4)> _;

注意:decltype returns f4 的实际类型。

注意:std::bind 的结果可以通过适当的签名分配给 std::function。对于您的第一个示例,它将是 std::function<int(Foo&)>

调用 std::bind 返回的类型是 unspecified by the standard.

每个实现都可以自由发明任何类型。

如果需要声明匹配f4类型的东西,可以使用decltype(f4)指定类型:

decltype(f4) f5;

以防万一您想要再次反省类型,这里有一个不错的库:Boost.TypeIndex 可以为您提供漂亮的类型。

对于 Clang 3.4

type_id_with_cvr<decltype(f4)>().pretty_name()

is

std::_Bind<std::_Mem_fn<int Foo::*> (std::_Placeholder<1>)>