Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
473 views
in Technique[技术] by (71.8m points)

c++ - When is required instantiation of function template definition?

After I read the answer for this question, I am still asking question. The answer talks about location of point of instantiation as defined in [temp.point] but it is not evaluated if the instantiations are required.

[temp.inst] specifies when a function template specialization instantiation is required, the general rule is:

An implementation shall not implicitly instantiate a function template, a variable template, a member template, a non-virtual member function, a member class,[...], unless such instantiation is required.

Moreover in some paragraph of this section of the standard, instantiation of declaration and instantiation of definition are considered separately.

Let's consider this code:

static void Yeap0(int);

template <class T>
void Yeap(T a){
    Yop(a);
}

template <class T>
auto Yeap2(T a){
    Yop(a);
    return 0;
}
namespace x{
    struct y{};
}

int main() {
    Yeap0(0);//ok no definition required here
    x::y ax{};
    Yeap(ax); //the declaration is sufficient, 
    Yeap2(ax); //need to deduce auto => definition required
               //compilation error
    return 0;
}

namespace x{
    void Yop(y){}
}

static void Yeap0(int){}

Gcc, Clang and MSVC produce only an error for Yeap2(ax), complaining that Yop is not defined at the point of instantiation of Yeap2.

But this error is not generated for Yeap(ax). From basic consideration this seems logical, only the declaration is needed, as for the none template function Yeap0.

But the lecture of [temp.inst]/4 let me perplex. It could be understood that the instantiation of Yeap is also required. But it seems that compilers have taken a more clever path.

Is the compilers behavior an extension?


Note: I will not accept the "no diagnostic required" answer. This would be an insult to intelligence: Could one believe that 3 compilers have taken special care to shut down diagnostics for case like Yeap(ax) but not for Yeap2(ax)?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The compiler complaining really comes from the fact that the function returns auto.

In the auto case you really hit

unless such instantiation is required.

which must come from the requirement dcl.spec.auto.

To verify that assessment you can replace in your code Yeap2 by:

template <class T>
auto Yeap2(T a){
    Yeap(a);
    return 0;
}

and there is no compilation error.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...