不能在没有模板的情况下声明 C++ 函数

cannot declare c++ function without template

我有一个相对较小的 c++ 项目,我决定制作一个 Utils 头文件,它只包含一些小的辅助函数等。当我声明使用模板的函数时一切正常,然后我尝试了制作一个不需要模板的函数,突然它不起作用。

我得到的结果是链接器错误;已在 (file).obj

中定义

我什至无法声明一个简单的 void 函数,没有模板的所有内容都会出现链接器错误。

我不知道是什么原因造成的。这是头文件的代码...提前致谢。

#pragma once

namespace Utils
{
    std::string GetActiveWindowTitle()
    {
        // This doesnt work either, also gives linker error.
        return active_window;
    }

    template<typename T>
    void Print(char * value, T printValue)
    {
        std::cout << value << ": " << printValue << std::endl;
    }

    template<typename T>
    void Print(T printValue)
    {
        std::cout << "DEBUG: " << printValue << std::endl;
    }

    void PrintStr(std::string str)
    {
        // This doesn't work because it doesnt have the template, it gives a linker error
        std::cout << "DEBUG: " << str.c_str() << std::endl;
    }
}

如果您将 header 包含在多个 cpp 中,函数将被定义多次,链接器将给出上述错误。参见 What is the difference between a definition and a declaration? or What are forward declarations in C++?

一个函数模板隐式inline。因此,当头文件中定义时,它并不违反ODR (One Definition Rule)。对于头文件中的非模板函数,您应该将它们定义为inline,或者在单独的翻译单元中定义它们。

所以,你可以这样做:

#pragma once

namespace Utils
{
    inline std::string GetActiveWindowTitle()
    {
        return active_window;
    }

    template<typename T>
    void Print(char * value, T printValue)
    {
        std::cout << value << ": " << printValue << std::endl;
    }

    template<typename T>
    void Print(T printValue)
    {
        std::cout << "DEBUG: " << printValue << std::endl;
    }

    inline void PrintStr(std::string str)
    {
        std::cout << "DEBUG: " << str.c_str() << std::endl;
    }
}

Inline keyword vs header definition