1

it's ok if I write class param as a template class.

struct fwd;

template <class T>
class param
{
public:
    void callinit()
    {
        p = std::make_shared<T>();
    }

    std::shared_ptr<T> p{nullptr};
};
param<fwd> pf;

but it will fail when the class param is not a template class: error: invalid application of 'sizeof' to incomplete type 'fwd' : std::aligned_storage<sizeof(_Tp), std::alignment_of<_Tp>::value> ^~~~~~~~~~

struct fwd;

class param
{
public:

    void callinit()
    {
        p = std::make_shared<fwd>();
    }

    std::shared_ptr<fwd> p{nullptr};
};

param pf;

actually the header file fwd.hpp never included in both of two conditions, but why the first condition succeed, but second failed?

Bonody
  • 19
  • 1
  • The answer is simple. Because you're not actually using the member function. Btw the program is **ill formed no diagnostic required** as you're not actually using the member function. On the other hand if you use the member function, the program will become ill-formed with diagnostic required and all compiler will give error then.[Demo](https://godbolt.org/z/81s7MnYnc) – Jason Nov 02 '22 at 10:04
  • 1
    [Member functions of a class template are instantiated only when required by a context, which means you will not see any error until you try to use `callinit`](https://stackoverflow.com/a/26123293/12002570). And if you use `callinit` you'll get error with all compilers. [Demo](https://godbolt.org/z/81s7MnYnc). This is explained in any [good c++ book](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list). – Jason Nov 02 '22 at 10:05
  • Note that there is no such thing as a “template class” in C++. C++ only has *class templates*. This matters: `param` is not a class. It is a *template*, i.e. you can *make* a class from it by instantiating it. And (indirectly) this is the reason for the difference you are observing. – Konrad Rudolph Nov 02 '22 at 10:10
  • 1
    @JasonLiam why is it illformed when the function is not called? Sure you have plenty of duplicates for that too – 463035818_is_not_an_ai Nov 02 '22 at 10:12
  • @463035818_is_not_a_number Let me quote you from the standard even though this is not a language-lawyer question and the dupe already explain the behavior of this program. Btw I've also previously explained to you why this kind of program is ill-formed no diagnostic required in one of the previous questions few months back. Give me 2-3 minutes to find that quote(or old question). – Jason Nov 02 '22 at 10:13
  • 1
    @463035818_is_not_a_number [Here is my old comment](https://stackoverflow.com/questions/73608314/c20-code-that-builds-in-clang-and-breaks-in-gcc#comment129984460_73608314) that explains the reason for one variation of the program. Basically compiler is free to give a diagnostic or not as long as the member function is not used. You can also refer to [temp.res.general#6.1] and [temp.res.general#6.4]. – Jason Nov 02 '22 at 10:21

0 Answers0