Template function func<T>
is designed to be used any where. It has the same function body for any T
. I want to write its body only once. But the function depends on the definition type<T>
to work properly, and there’s no definition of type<T>
in some context. See the following example(in C++17):
/// type.h
#include <stddef.h>
#include <stdint.h>
#include <type_traits>
template<typename T, typename = void>
struct type;
template<typename T>
size_t func() {
return type<T>::magic;
}
template<typename T>
struct type<T, std::enable_if_t<std::is_arithmetic_v<T>>> {
static constexpr size_t magic = sizeof(T) * 2;
};
/// my_type.h
struct MyStruct {
int a;
static void Dummy();
};
/// my_type.cpp
#include "my_type.h"
#include "type.h"
template<>
struct type<MyStruct> {
static constexpr size_t magic = 123;
};
void MyStruct::Dummy() {
(void)func<MyStruct>();
}
/// main.cpp
#include "my_type.h"
#include "type.h"
int main(int argc, char **argv) {
func<int>(); // OK
func<MyStruct>(); // Error
}
How could I manage to do that:
- Write the body of
func<T>
only once. - Make it possible to invoke
func<T>
whentype<T>
is incomplete.
note: There’s a
Dummy
function, which is used force the compiler generate code forfunc<MyStruct>
so that the linker will happy.