OiO.lk Community platform!

Oio.lk is an excellent forum for developers, providing a wide range of resources, discussions, and support for those in the developer community. Join oio.lk today to connect with like-minded professionals, share insights, and stay updated on the latest trends and technologies in the development field.
  You need to log in or register to access the solved answers to this problem.
  • You have reached the maximum number of guest views allowed
  • Please register below to remove this limitation

Why does this static_assert on a pointer to an incomplete type in a templated function apparently work?

  • Thread starter Thread starter James Picone
  • Start date Start date
J

James Picone

Guest
In the process of replacing a static_assert in a templated function with a requires statement, we discovered that firstly, the function was occasionally being used on an incomplete type, and that secondly, this apparently compiled. The version with the requires statement, of course, is illegal.

Here's a simple version of the apparently-functioning static_assert:

Code:
#include <type_traits>

struct Bar {};

template<typename T>
inline Bar* AsBar(T* ptr)
{
    static_assert(std::is_convertible_v<T*, Bar*>);
    return (Bar*)ptr;
}

struct Foo;

void DoThing(Foo* f)
{
    AsBar(f);
}

struct Foo : public Bar {};

This surprises me! My model of how the templating works is that at the point of instantiation, all the code is generated, and at that point we invoked std::is_convertible_v on an incomplete type, which is undefined behaviour. Sticking a non-templated version of the same function at that point fails.

So I have some questions:

Firstly, does the templated static_assert that is working for an incomplete type have defined behaviour? Or are we simply 'getting lucky' with undefined behaviour?

Secondly, if it's defined, why? What is incomplete about my understanding of templates?
Continue reading...
 

Latest posts

J
Replies
0
Views
1
jbowerbir
J
Top