Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Template definition in .h file requires me to include .h files, C++

Tags:

c++

templates

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...
}
like image 244
sadcat_1 Avatar asked Oct 26 '25 05:10

sadcat_1


1 Answers

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;
}
like image 83
Caleth Avatar answered Oct 27 '25 20:10

Caleth



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!