2

I have the following piece of code where I'm using two template functions to access elements of a tuple. The print function will have code that requires more files to be #includeed and I don't want code bloating if I was to include it in a header, given that template functions are defined in a header. Is there a way I could move the function definitions into a cpp file and avoid recursive / duplicate inclusions?

#include <stdio.h>
#include <tuple>
#include <iostream>

template<std::size_t I = 0, typename... Tp>
inline typename std::enable_if<(I >= sizeof...(Tp)), void>::type
print(std::tuple<Tp...> &/*t*/) { }
        
template<std::size_t I = 0, typename... Tp>
inline typename std::enable_if<(I < sizeof...(Tp)), void>::type
print(std::tuple<Tp...> &t) { 
    std::cout << std::get<I>(t) << std::endl; 
}
        
int main()
{
    std::tuple<int, std::string, char> t = std::make_tuple(10, "Hello", 'A');
    print<0>(t);
    print<1>(t);
    print<2>(t);
    print<4>(t);
    return 0;
}
SagunKho
  • 985
  • 10
  • 26
  • 1
    Unless you manually want to instantiate the template for all the template parameters you would use, no: https://stackoverflow.com/questions/495021/why-can-templates-only-be-implemented-in-the-header-file – NathanOliver Jan 25 '21 at 14:56
  • Does this answer your question? [Storing C++ template function definitions in a .CPP file](https://stackoverflow.com/questions/115703/storing-c-template-function-definitions-in-a-cpp-file) – underscore_d Jan 25 '21 at 14:57
  • For the printing i would implement the output stream operator for the types you need to print. So your implementation would be complete and somewhere you define how the objects need to be written to the stream. – Zaiborg Jan 25 '21 at 14:58
  • @NathanOliver How would I instantiate the template for one parameter for example? For instance i have a function - `template template inline typename std::enable_if<(I < sizeof...(Tp)), void>::type BasicAttributeNotifier::notify(std::tuple &t) { }` – SagunKho Jan 25 '21 at 15:08
  • 1
    You would need to do something like [this](https://stackoverflow.com/questions/8302407/c-explicit-templated-function-instantiation-for-templated-class-of-different-t) to instantiate the class and then the member function. – NathanOliver Jan 25 '21 at 15:19
  • Does this answer your question? [How do I explicitly instantiate a template function?](https://stackoverflow.com/questions/4933056/how-do-i-explicitly-instantiate-a-template-function) – Zak Jan 18 '23 at 01:37

0 Answers0