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

标签 c++ 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: 我想声明一个绑定(bind)到 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类型的东西,你可以使用decltype(f4)来指定类型:

decltype(f4) f5;

关于c++ - auto 推导的那个类型是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28146786/

相关文章:

c++ - 是否可以在 GPU 中运行一段纯 C++ 代码

c++ - 如何从 C++ 中的函数返回结构?

c++ - 矢量化是什么意思?

c++ - `auto pp` 和 `auto *ppp` 有什么区别?

c# - C++ 模板和 Java/C# 泛型之间的区别是什么?限制是什么?

c++ - For循环索引类型推导最佳实践

c++ - 使用 static_cast<>() 声明变量时使用 auto 的目的是什么?

c++ - 具有三元运算符和 nullptr 的 auto

c++ - 在 lambda 函数中使用 auto

c++17 - C++模板代码生成错误: use of 'some_variable' before deduction of 'auto'