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

Utility function won't initialize in .h file and define in main.cpp

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

我试过正常的方法,只是先在 main.h 中定义它,然后在我的 main.cpp

中填写其余部分

main.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();
}

main.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 中,否则 "undefined reference to function" stringify 总是出现错误。我在这里错过了什么?我一直在阅读文档,但似乎无法理解。

请注意,在函数参数中使用 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?

当您将参数定义为 auto 时,编译器将在后台使用模板:

你的函数:

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

等于:

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

并且需要定义模板函数(不仅仅是声明)。所以,选择是在头文件中定义它。