When is required instantiation of function template definition?

北慕城南 提交于 2019-12-13 10:01:35

问题


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)?


回答1:


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.



来源:https://stackoverflow.com/questions/52394125/when-is-required-instantiation-of-function-template-definition

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!