c++ - 实用函数不会在 .h 文件中初始化并在 main.cpp 中定义

标签 c++ auto

我刚刚学习 C++,遇到了 Sublime Text 控制台调试器无法为我解决的问题。我有一个带有两个参数的 stringify 函数,一个是 const auto& arr,一个是 const std::string& ch。我希望能够在我的 main.h 文件中初始化它,我将它导入到我的项目的每个 .cpp 文件中,以便它可用于全局范围。

我已经尝试过正常的方法,只是先在 main.h 中定义它,然后在我的 main.cpp 中填写其余部分

主要.cpp

std::string stringify(const auto& arr, const std::string& ch)
{
    std::stringstream ss;
    unsigned i = 0;
    for (auto& element : arr) {
        ++i;
        // add element to s
        ss << element;
        // if element isnt the last one.
        (i != arr.size()) ? ss << ch : ss;
    }
    return ss.str();
}

主要.h

#ifndef MAIN_H
#define MAIN_H

#include <iostream>
#include <string>
#include <sstream>
#include <array>
#include <vector>
#include <iterator>
#include <algorithm>

std::string stringify(const auto& arr, const std::string& ch);

#endif // MAIN_H

无论我尝试什么,我都会不断收到“未定义的函数引用”字符串化错误,除非我将完整的函数定义放在 main.h 中。我在这里错过了什么?我一直在阅读文档,但似乎无法弄明白。

最佳答案

注意在函数参数中使用 auto,例如 const auto& arr,目前不是标准 C++。它在 C++20 中有效,但一些编译器已经将其作为扩展实现用于其他 C++ 版本。

不过,它实际上做的是将函数变成一个函数模板,因为现在需要从函数参数中推导出参数的实际类型。所以声明

std::string stringify(const auto& arr, const std::string& ch);

本质上等同于

template <typename T>
std::string stringify(const T& arr, const std::string& ch);

因为你的函数就像一个模板,它的定义需要在头文件中,这样编译器就可以在它与新类型的 arr 一起使用时根据需要实例化它。 (参见 Why can templates only be implemented in the header file?)

关于c++ - 实用函数不会在 .h 文件中初始化并在 main.cpp 中定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56200615/

相关文章:

C++:使用 C++14 通用 lambda boost fusion fold

C++ 对齐/移位问题

c++ - 将 D 库链接到 C++ 代码

c++ - 为 C++ Linux 应用程序创建隐藏配置文件

由 nullptr 初始化的 C++11 自动变量

c++ - 为什么 C++ 不允许在一个 auto 语句中使用多种类型?

c++ - 如何在二进制文件中设置内置版本号?

c++ - 字符串复制函数产生 `pointer being freed was not allocated`

c++ - 我可以在 g++ 4.4 中使用 auto 吗?

c++ - 为什么这个变量在 C++14 中的 g++ 中没有被推断为 initializer_list?