I am learning to use template functions and organize my code in multiple files. I looked at Why can templates only be implemented in the header file? where they point out I should implement my template-functions in the header; I also looked at C++ inline functions: declare as such, define as such, or both? Why? so I know I should define fully specialized functions as inline in the header; and I looked at Why use a “tpp” file when implementing templated functions and classes defined in a header? where they suggest to define the templates (and also the fully specialized templates?) in a separate my.tpp
and add #include "my.tpp"
at the end of my header.
Now my question as a completely beginner is: How do I combine all this with regular functions.
Imagine the following:
#ifndef IVAL_H
#define IVAL_H
//Function to determine if input string is of a given type
template<typename T>
bool is_type(std::string);
//Specialization when testing integer
//As I also want to accept e.g. 4.0000 as an integer
template<>
bool is_type<int>(std::string);
//Function to get a given type
template<typename T>
T get_type(std::string);
//Finally a normal function to ask for [y/n]
bool yesNo(std::string prompt);
//Include templates definitions
#include"ival.tpp"
#endif /*IVAL_H*/
Then I have, as suggested in the questions quoted above:
//in ival.tpp
#ifndef IVAL_TPP
#define IVAL_TPP
template<typename T>
bool is_type(std::string input)
{
//How to validate input
}
template<>
bool inline is_type<int>(std::string input)
{
\\How to validate when integer
}
template<typename T>
T get_type(std::string prompt)
{
//How to keep asking until valid input
//Using is_type
}
#endif /*IVAL_H*/
And finaly as a .cpp
my normal function:
//in ival.cpp
#include "ival.h"
bool yesNo(std::string prompt)
{
//How to ask for [y/n]
//Using get_type<char>
}
This causes some confusion as to how is the correct way of organizing my functions. When in a header we have both template functions and normal functions, is the normal thing to do what I did above? (different source file for normal functions), are the fully specialized functions treated as a template (i.e. defined inline in the file where all templates are) or as a function (i.e. defined just in .cpp as all other functions).
Is what I did more convenient over defining the template functions in .cpp and explicit instantiate to char, int, double, float
, and std::string