Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Declare function template instantiation without the template

Tags:

c++

templates

Is it possible to declare that a symbol is an explicit instantiation of a function template, without defining the function template first?

It would express to the compiler that there exists a function template in another translation unit that is instantiated somewhere, and we want to call the instantiated function.

// declaration of instantiation, perhaps it would look like one of these:
// template<typename> void foo(int);
// template<typename> void foo<int>(int);

void bar(int i) {
    // definition of function unknown to caller, it shouldn't matter
    foo(i);

    // either that or this perhaps:
    foo<int>(i);
}

Is there a technical reason this can't be done or is it just for lack of syntax? Is there a reason that it's not possible to provide sufficient information in a declaration to generate calls to an instantiated function template?

There is no Y behind this X. This question is meant literally. It's an abstract question about the C++ language. I could provide an example that doesn't compile but that would just be a distraction.

The question is also not about specialization per se. Whether the template was specialized shouldn't matter. This question is only concerned with declaring that a template exists and that it was instantiated.

Related question: How do I explicitly instantiate a template function? - however that does not solve this problem, as it requires the full template definition to be visible.

like image 752
Praxeolitic Avatar asked Jan 29 '26 03:01

Praxeolitic


1 Answers

You can use "extern template" here. It tells the compiler not to instantiate it in every translation units. This is part of C++11 enhancements. For example, we may declare the template in a header file a.hpp as

// a.hpp
template <class T>
T fun(T& a);

Then in a.cpp

// a.cpp
#include "a.hpp"
extern template int fun(int&);
int main()
{
   int a = 100;
   return fun(100);
}

And in b.cpp we can actually instantiate the template:

// b.cpp
#include "a.hpp"

template <>
int fun(int& x)
{
    return x + 1;
}
like image 184
Nipun Talukdar Avatar answered Jan 31 '26 18:01

Nipun Talukdar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!