I'm trying to create a template function taking a typename. I want to specialize this templates for some basic types like int
, long
, string
and double
. For all others types, i need to have a specialized code for class/struct, and a default code for others types.
My current code is this one :
// Declaration
template <typename T, typename enable_if<is_class<T>::value>::type = 0>
void test(T& value);
template <typename T, typename enable_if<!is_class<T>::value>::type = 0>
void test(T& value);
template <> // What am i supposed to write here ?
void test<int>(int& value);
// Definition
template <typename T, typename enable_if<is_class<T>::value>::type = 0>
void test(T& value) {
cout << "Class/struct test" << endl;
}
template <typename T, typename enable_if<!is_class<T>::value>::type = 0>
void test(T& value) {
cout << "Other types test" << endl;
}
template <>
void test<int>(int& value) {
cout << "int test" << endl;
}
This code won't compile. I can't figure what am i suppoed to write in the int
specialized template.
I'm trying to use the examples from this documentation, but i'm unable to make it work.
is_class<T>::value
is true,enable_if<is_class<T>::value>::type
isvoid
. You try to assign0
tovoid
. – Seventeenthenable_if
in the header and explicitly instantiating the template function in the source file but I got an undefined symbol because theenable_if
becomes part of the symbol in the binary. When you explicitly instantiate the function, you can't addenable_if
, so it has to stay undefined. The example here is different because thetest
function is declared and defined explicitly forint
, hence theenable_if
is not part of the symbol in the generated code, so the answers help – Tombac