Tristan Brindle
Tristan Brindle

Reputation: 16824

Function templates: extern template vs explicit specialisation

Consider the following function template declaration:

template <typename T, typename = std::enable_if_t<std::is_same_v<T, int>>>
void foo(T i);

There is only one possible valid instantiation of this template, namely with T = int. I'd like to put this definition in an implementation file. I can think of two possible ways of doing so. (If you're wondering why on earth I'd do this rather than just saying void foo(int i), it's because the template version prevents implicit conversions at the call site.)

Approach 1:

I can use an extern template declaration to tell other TUs that foo<int>() is instantiated elsewhere:

// In foo.hpp
template <typename T, typename = std::enable_if_t<std::is_same_v<T, int>>>
void foo(T i);

extern template void foo(int);

// In foo.cpp
template <typename T, typename>
void foo(T i) { ... } // full template definition

template void foo(int); // explicit instantiation with T = int

Approach 2:

I can provide an explicit specialisation for the int case:

// In foo.hpp
template <typename T, typename = std::enable_if_t<std::is_same_v<T, int>>>
void foo(T i);

template <> void foo(int i); // explicit specialisation declaration (*)

// In foo.cpp
template <>
void foo(int i) { ... } // explicit specialisation definition

Questions:

Upvotes: 9

Views: 3152

Answers (1)

NathanOliver
NathanOliver

Reputation: 180560

There is a third approach. In approach 3 you specify the function you want to have and the you add a template overload and mark that as delete. That looks like

void foo(int i)
{
    // stuff
}

template <typename T>
void foo(T t) = delete;

Since the template version will match all types exactly it will be preferred in all cases except int since a non template exact match is preferred to a template one. So you will only be able to call foo with an int and all other types will give you an error that they are trying to call the deleted function void foo(T t).

Live Example

Upvotes: 6

Related Questions