We know that template function's definition should go in an .h file, normally. I have a template function definition that requires me to include several more .h files in my .h file. This means that every unit that will include my .h file will include those several .h files as well.
Is there a way to overcome this?
I thought about forward declaration, but in my case it's not really viable (I want to use std::filesystem::file_size()
without including <filesystem>
).
Edit: I'm adding a minimum example to what I'm trying to do
class A{
public:
template <typename T>
static T getValueFromFile(std::streampos byte_position);
}
template <typename T>
T A::getValueFromFile(std::streampos byte_position){
std::fstream file (PATH, std::ios::in | std::ios::out | std::ios::binary);
if(!file){
exit(-1);
}
if (byte_position < 0 || std::filesystem::file_size(PATH) <= byte_position){
exit(-1);
}
// Getting value from file and returning it logic...
}
We know that template function's definition should go in an .h file, normally. I have a template function definition that requires me to include several more .h files in my .h file. This means that every unit that will include my .h file will include those several .h files as well.
Is there a way to overcome this?
I thought about forward declaration, but in my case it's not really viable (I want to use std::filesystem::file_size()
without including <filesystem>
).
Edit: I'm adding a minimum example to what I'm trying to do
class A{
public:
template <typename T>
static T getValueFromFile(std::streampos byte_position);
}
template <typename T>
T A::getValueFromFile(std::streampos byte_position){
std::fstream file (PATH, std::ios::in | std::ios::out | std::ios::binary);
if(!file){
exit(-1);
}
if (byte_position < 0 || std::filesystem::file_size(PATH) <= byte_position){
exit(-1);
}
// Getting value from file and returning it logic...
}
You can move the parts that don't depend on T
into a non-template function, and call that from your template.
For the parts that depend on T
, there isn't a way to overcome it.
A.h
class A{
public:
template <typename T>
static T getValueFromFile(std::streampos byte_position);
private:
static std::fstream getFile(std::streampos byte_position);
}
template <typename T>
T A::getValueFromFile(std::streampos byte_position){
std::fstream file = getFile(byte_position);
// Getting value from file and returning it logic...
}
A.cpp
#include <filesystem>
std::fstream A::getFile(std::streampos byte_position) {
std::fstream file (PATH, std::ios::in | std::ios::out | std::ios::binary);
if(!file){
exit(-1);
}
if (byte_position < 0 || std::filesystem::file_size(PATH) <= byte_position){
exit(-1);
}
return file;
}
getValueFromFile
withrequires std::is_trivially_copyable<T>
– Caleth Commented Mar 11 at 14:48