I don't want to write a .cpp file for every simple c++ class.
when I write a class definition and declaration in a single .hpp file,
the linker complains about multiple definition of member functions which are not implemented inside the body of the class.
So I use templates to get rid of linker complaints:
// 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;
And then I can simply use log class in multiple .cpp files without linker complaints.
Is there something fundamentally wrong with this method?
Edit: even when i use this method will member functions become inline ?
If some class doesn't need to be a template, don't make it a template just to "get rid of the linker's complains". Just use proper coding techniques, like providing inline defintions of member functions:
// 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;
}
If you provide the function's body inside the class definition, then there's no need to specify the keyword 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;
}
};
As you want the functions to be defined in headers (which are included in multiple source files, which leads to multiple definitions in your case), you should make the functions inline.
2 options:
inline - do not separate the function definitionsinline - manually add inline keyword in front of the definitionsUsing templates just to "work-around" this error is not a good idea. Use templates only when you need them.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With