c++ - 返回 'auto' 的函数在定义之前不能使用

标签 c++ function auto

我有一个用 Visual C++ 创建的 DLL 项目和一个 CLR 项目。 在我的 DLL 项目中,我导出了一个“auto”类型的函数。

员工.h

extern "C" STAFFS_API auto GetStaffMap();

如果staff.cpp它有一个std::map返回类型。

std::map<int, std::string> staffMap;
auto GetStaffMap() 
{
  return staffMap;
}

现在在我的 CLR 应用程序中, 我称这个函数为:

#include <map>
#include "Staff.h"
std::map<int, std::string> staffMap = Staffs::GetStaffMap();

当我编译该程序时,出现错误:

C3779 'Staffs::GetStaffMap': a function that returns 'auto' cannot be used before it is defined.

更新

我试过了, 员工.h

extern "C" STAFFS_API auto GetStaffMap() -> std::map<int, std::string>;

员工.cpp

extern "C" auto GetStaffMap() -> std::map<int, std::string> {
  return staffMap;
}

但仍然有编译错误:

Error   C2526   'GetStaffMap': C linkage function cannot return C++ class 'std::map<int,std::string,std::less<int>,std::allocator<std::pair<const _Kty,_Ty>>>'  AmsCppRest  c:\users\laptop-attendance\source\repos\amscpprest\amscpprest\staff.h

Error   C2556   'std::map<int,std::string,std::less<int>,std::allocator<std::pair<const _Kty,_Ty>>> Staffs::GetStaffMap(void)': overloaded function differs only by return type from 'void Staffs::GetStaffMap(void)'   AmsCppRest  c:\users\laptop-attendance\source\repos\amscpprest\amscpprest\staff.cpp

Error  C2371 'Staffs::GetStaffMap': redefinition; different basic types

最佳答案

auto 不会延迟查找函数的返回类型。它只是让编译器自动查看实现以找出它是什么。您必须在 header 中手动声明返回类型,因为包含 header 的代码必须知道返回类型是什么。

关于c++ - 返回 'auto' 的函数在定义之前不能使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50147561/

相关文章:

function - 使用百分号作为前缀运算符名称的一部分

c++ - 在 C++11 中使用 decltype() 时出错(在 gcc 4.7.0 中创建不透明的错误消息)

c++ - 从 int* 到 int& 的转换

c++ - 在下面的static_strlen 实现中,为什么需要用& 和括号括住str?

c - 使用带有指针的冒泡排序按升序排序

c++ - 为 auto 键入别名

c++ - 自动功能必须在使用前定义

C++ 本地容器

c++ - 在 BOOST 中禁用异常?

c++ - 函数参数的销毁顺序是什么?