4

The general issue is why does this compile:

#include <cstddef>

template<typename T>
std::size_t size() { return sizeof(T); }

struct x;

template std::size_t size<x>();
// Or an implicit instantiation like:
int main() { return size<x>(); }

struct x {};

even though the definition of x appear after the explicit instantiation? It seems like the instantiation means that sizeof(x) is used with an incomplete type x.

If it is replaced with a specialization (or with a non-template), it fails to compile as expected:

#include <cstddef>

template<typename T>
constexpr std::size_t size() { return sizeof(T); }

struct x;
template<> std::size_t size<x>() {
    return sizeof(x);  // error: invalid application of 'sizeof' to incomplete type 'x'
}

struct x {};

What gives? For context, this arose because standard libraries use sizeof(T)>0 as a "is T complete" check, but T can be completed after the check and it will still pass.

Artyer
  • 31,034
  • 3
  • 47
  • 75
  • So it appears that standard library vendors are wrong to use `static_assert(sizeof(T)>0)` when the standard mandates that a type is complete, since there is no diagnostic – Artyer Aug 20 '21 at 13:07
  • I'd bet that if you examine the *specification* of those standard library components you'd find "type is complete" as preconditions (the violation of which results in UB). – StoryTeller - Unslander Monica Aug 20 '21 at 13:08
  • They aren't wrong. They give a best effort. Violating preconditions is on client code, not standard library vendors. – StoryTeller - Unslander Monica Aug 20 '21 at 13:08
  • @StoryTeller-UnslanderMonica some standard library components are ill-formed with incomplete types, which require a diagnostic, but there is none (e.g., https://godbolt.org/z/T1M4d57Mx has no errors, even though that would require a diagnostic due to [\[unique.ptr.dltr.dflt\]p3](https://eel.is/c++draft/unique.ptr.dltr#dflt-3) according to this question: https://stackoverflow.com/q/63541611) – Artyer Aug 20 '21 at 13:13
  • Then it's potentially a standard defect. – StoryTeller - Unslander Monica Aug 20 '21 at 13:25

0 Answers0