zwhconst
zwhconst

Reputation: 1513

If I forward declare a function template, may I put the definition after the calling site and not explicit instantiate it at all?

In a header file of a large project, I have to forward declare a function template before the calling site. The code boils down to this:

//H1.h

#pragma once

template <typename>
void f();

inline void g()
{
    f<void>();
}
//POI #1

template <typename>
void f()
{}
//TU1.cpp

#include "H1.h"

void func1()
{
    g();
}

//(End of TU) POI #2
//TU2.cpp

#include "H1.h"

void func2()
{
    g();
}

//(End of TU) POI #3

As I understand, #1, #2 and #3 are three POIs for f. At POI #1, f is not defined yet. After the definition of f, there is no explicit instantiation to tell the compiler to instantiate f<void> specifically. Does the compiler remember to generate code for f<void> at the end of TU? The testing result is yes, at least when using GCC, clang, or MSVC.

But the question is: is this declare-call-define pattern for function template standard conformant?

I'm not a standard expert but I searched the standard text to look for relevant words, and only found this rule for when using explicit instantiation. But I'm not sure the case when the template is implicit instantiated.

Upvotes: 4

Views: 158

Answers (0)

Related Questions