I would like to combine return type deduction and explicit template instantiation (e.g. f<int> instead of template<typename T> f<T>). The example below shows how this can be done in one file play with code.
#include <type_traits>
#include <iostream>
#include <string>
enum Enum { String, Int };
template <Enum E>
auto f();
template <>
auto f<Enum::String> () {
return "string";
}
template <>
auto f<Enum::Int> () {
return 2;
}
int main()
{
const Enum e = Enum::String;
auto a = f<e>();
const Enum g = Enum::Int;
auto b = f<g>();
return 0;
}
Question: How can I combine return type deduction, template instantiation with header files?
What I would like:
// f.hpp
template<Enum E> auto f();
// f.cpp
f<Enum::Int> f() { // ...
// other_file.cpp
#include "f.hpp"
auto a = f<Enum::Int>();
Error: function 'f<Enum::Int>' with deduced return type cannot be used before it is defined.
Ideas:
IMO the error makes sense since the function instantiation is not in the header and was thus not included in other_file.cpp.
I am unable to write the instantiations in the f.hpp since they are instantiations (obviously).
I thought about using inline, but that did not help (why?).
Can anyone help me?
Actually, the 2 definitions you provide for
fare called explicit specializations. You cannot define them in a dedicated implementation file because the compiler must know their return type.In this situation a possible work around, if you want to use deduced return type, is to pack the specialization definition within the primary template definition using a constexpr if statement, and then use explicit template instantiation:
Inside
f.hpp:Inside
f.cpp: