I was looking for a way to separate declaration and implementation in a template class (our professor bitches about this a lot) and I managed to find what looks to be a solution, here's the code (it also includes separation for single functions btw):
Template.h:
#pragma once
template <typename T>
void foo(T arg);
template <typename T> class test {
T data;
public:
test(T arg);
T getData();
};
#include "Template.ipp"
Template.ipp:
#include "Template.h"
#include <iostream>
template <typename T>
void foo(T arg) {
arg = arg + 1;
std::cout << arg << std::endl;
}
template <typename T>
test<T>::test(T arg) : data(arg) {}
template <typename T>
T test<T>::getData() {
return data;
}
main.cpp:
#include "Template.h"
#include "Template.h" // limit testing to see if #pragma once in Template.ipp is necessary
#include <iostream>
int main() {
int xd = 3;
foo(xd);
std::cout << xd << std::endl;
char xdd = 'a';
foo(xdd);
std::cout << xdd << std::endl;
test<int> testxd(xd);
std::cout << testxd.getData() << std::endl;
test<char> testxdd(xdd);
std::cout << testxdd.getData() << std::endl;
}
The code does compile in Visual Studio and the output is as expected
Output:
4
3
b
a
3
a
My question is: does the mutual inclusion risk to bite me in the ass if I use it in a bigger project? Is there any obvious downside to this approach? I know that putting the definition in the header is the standard practice so if I had a choice I'd rather go for it Also, is there a convention on the naming of the file? I used .ipp but I see that there's also .tpp, is there a difference in how they're used or are they used interchangeably?
P.S. this is my first question, please don't blast me too much