没有.cpp文件的C++类?

ami*_*min 2 c++ templates class header-files

我不想.cpp为每个简单的c ++类编写文件.

当我在单个.hpp文件中编写类定义和声明时,链接器会抱怨成员函数的多个定义,这些定义并未在类的主体内实现.

所以我使用模板来摆脱链接器投诉:

// log.hpp file
template<typename T>
class log_t {
private:
    int m_cnt = 0;
public:
    void log();
};

template<typename T>
void log_t<T>::log() {
    std::cout << ++m_cnt << std::endl;
}

// some random type (int)
typedef log_t<int> log;
Run Code Online (Sandbox Code Playgroud)

然后我可以简单地log在多个.cpp文件中使用class 而不需要链接器投诉.

这种方法有什么根本性的错误吗?

编辑:即使我使用此方法会将成员函数变为内联吗?

Mr.*_*C64 5

如果某个类不需要是模板,请不要将其作为模板只是为了"摆脱链接器的抱怨".只需使用适当的编码技术,例如提供成员函数的内联定义:

// log.hpp file

#pragma once

#include <iostream> // For std::cout, std::endl

class log {
private:
    static int m_cnt = 0;
public:
    log();
};

// Note "inline" here:
inline log::log() {
    std::cout << ++m_cnt << std::endl;
}
Run Code Online (Sandbox Code Playgroud)

如果在类定义中提供函数体,则无需指定关键字inline:

// log.hpp file

#pragma once

#include <iostream> // For std::cout, std::endl

class log {
private:
    static int m_cnt = 0;
public:
    // Function body inserted here (no need for "inline"):
    log() {
        std::cout << ++m_cnt << std::endl;        
    }
};
Run Code Online (Sandbox Code Playgroud)