Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 6793781
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 26, 20262026-05-26T18:08:29+00:00 2026-05-26T18:08:29+00:00

I need a way to verify during compile time that upcast/downcast of a pointer

  • 0

I need a way to verify during compile time that upcast/downcast of a pointer to another class (either derived or base) does not change the pointer value. That is, the cast is equivalent to reinterpret_cast.

To be concrete, the scenario is the following: I have a Base class and a Derived class (obviously derived from Base). There is also a template Wrapper class that consists of a pointer to the class specified as a template parameter.

class Base
{
    // ...
};

class Derived
    :public Base
{
    // ...
};

template <class T>
class Wrapper
{
    T* m_pObj;
    // ...
};

In some situations I have a variable of type Wrapper<Derived>, and I’d like to call a function that receives a (const) reference ro Wrapper<Base>. Obviously there is no automatic cast here, Wrapper<Derived> is not derived from Wrapper<Base>.

void SomeFunc(const Wrapper<Base>&);

Wrapper<Derived> myWrapper;
// ...

SomeFunc(myWrapper); // compilation error here

There are ways to handle this situation within the scope of the standard C++. Like this for example:

Derived* pDerived = myWrapper.Detach();

Wrapper<Base> myBaseWrapper;
myBaseWrapper.Attach(pDerived);

SomeFunc(myBaseWrapper);

myBaseWrapper.Detach();
myWrapper.Attach(pDerived);

But I don’t like this. Not only this demands an awkward syntax, but it also produces an extra code, because Wrapper has a non-trivial d’tor (as you may guessed), and I’m using exception handling. OTOH if the pointer to Base and Derived are the same (like in this example, since there’s no multiple inheritance) – one may just cast myWrapper to the needed type and call SomeFunc, and it will work!

Hence I’ve added the following to Wrapper:

template <class T>
class Wrapper
{
    T* m_pObj;
    // ...

    typedef T WrappedType;


    template <class TT>
    TT& DownCast()
    {
        const TT::WrappedType* p = m_pObj; // Ensures GuardType indeed inherits from TT::WrappedType

        // The following will crash/fail if the cast between the types is not equivalent to reinterpret_cast
        ASSERT(PBYTE((WrappedType*)(1)) == PBYTE((TT::WrappedType*)(WrappedType*)(1)));

        return (TT&) *this; // brute-force case
    }

    template <class TT> operator const Wrapper<TT>& () const
    {
        return DownCast<Wrapper<TT> >();
    }
};


Wrapper<Derived> myWrapper;
// ...

// Now the following compiles and works:
SomeFunc(myWrapper);

The problem is that in some cases the brute-force cast is not valid. For instance in this case:

class Base
{
    // ...
};

class Derived
    :public AnotherBase
    ,public Base
{
    // ...
};

Here the value of the pointer to Base differs from Derived. Hence Wrapper<Derived> is not equivalent to Wrapper<Base>.

I’d like to detect and prevent attempts of such an invalid downcast. I’ve added the verification (as you may see), but it works in run-time. That is, the code would compile and run, and during the runtime there’ll be a crash (or a failed assertion) in debug build.

This is fine, but I’d like to catch this during compile time and fail the build. A sort of a STATIC_ASSERT.

Is there a way to achieve this?

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-26T18:08:30+00:00Added an answer on May 26, 2026 at 6:08 pm

    Short answer: no.

    Long answer:

    There is limited introspection available at compilation time, and you can for example (using function overload resolution) detects if a class B is an accessible base class of another class D.

    However that’s about it.

    The Standard does not require full introspection, and notably:

    • you cannot list the (direct) base classes of a class
    • you cannot know whether a class has only one or several base classes
    • you cannot even know if a base class is the first base or not

    And of course, there is the issue that the object layout is more or less unspecified, anyway (though C++11 adds the ability to distinguish between trivial layout and class with virtual methods if I remember correctly, which helps a bit here!)

    Using Clang, and its AST inspection capabilities, I think you could write a dedicated checker, but this seems quite complicated, and is of course totally non-portable.

    Therefore, despite your bold claim P.S. Please don’t reply with “why do you want to do this” or “this is against the standard”. I know what what all this for, and I have my reasons to do this., you will have to adapt your ways.

    Of course, if we were given a broader picture of your usage of this class, we might be able to pool our brains together and help you figure a better solution.


    How to implement a similar system ?

    I would propose, first, a simple solution:

    • Wrapper<T> is the owner class, non-copyable, non-convertible
    • WrapperRef<U> implements a proxy over an existing Wrapper<T> (as long as T* is convertible to U*) and provide the conversions facilities.

    We will use the fact that all pointers to be manipulated inherit from UnkDisposable (this is a crucial information!)

    Code:

    namespace details {
      struct WrapperDeleter {
        void operator()(UnkDisposable* u) { if (u) { u->Release(); } }
      };
    
    
      typedef std::unique_ptr<UnkDisposable, WrapperDeleter> WrapperImpl;
    }
    
    template <typename T>
    class Wrapper {
    public:
      Wrapper(): _data() {}
    
      Wrapper(T* t): _data(t) {}
    
      Wrapper(Wrapper&& right): _data() {
        using std::swap;
        swap(_data, right._data);
      }
    
      Wrapper& operator=(Wrapper&& right) {
        using std::swap;
        swap(_data, right._data);
        return *this;
      }
    
      T* Get() const { return static_cast<T*>(_data.get()); }
    
      void Attach(T* t) { _data.reset(t); }
      void Detach() { _data.release(); }
    
    private:
      WrapperImpl _data;
    }; // class Wrapper<T>
    

    Now that we laid down the foundations, we can make our adaptive proxy. Because we will only manipulate everything through WrapperImpl, we ensure the type-safety (and the meaningful-ness of our static_cast<T*>) by checking conversions through std::enable_if and std::is_base_of in the template constructors:

    template <typename T>
    class WrapperRef {
    public:
      template <typename U>
      WrapperRef(Wrapper<U>& w,
        std::enable_if_c< std::is_base_of<T, U> >::value* = 0):
        _ref(w._data) {}
    
      // Regular
      WrapperRef(WrapperRef&& right): _ref(right._ref) {}
      WrapperRef(WrapperRef const& right): _ref(right._ref) {}
    
      WrapperRef& operator=(WrapperRef right) {
        using std::swap;
        swap(_ref, right._ref);
        return *this;
      }
    
      // template
      template <typename U>
      WrapperRef(WrapperRef<U>&& right,
        std::enable_if_c< std::is_base_of<T, U> >::value* = 0):
        _ref(right._ref) {}
    
      template <typename U>
      WrapperRef(WrapperRef<U> const& right,
        std::enable_if_c< std::is_base_of<T, U> >::value* = 0):
        _ref(right._ref) {}
    
      T* Get() const { return static_cast<T*>(_ref.get()); }
    
      void Detach() { _ref.release(); }
    
    private:
      WrapperImpl& _ref;
    }; // class WrapperRef<T>
    

    It might be tweaked according to your needs, for example you could remove the ability to Copy and Move the WrapperRef class to avoid situation where it point to a no longer valid Wrapper.

    On the other hand, you could also enrich this using a shared_ptr/weak_ptr approach in order to be able to copy and move the wrapper and still guarantee the availability (but beware of memory leaks).

    Note: it is intentional that WrapperRef does not provide an Attach method, such a method cannot be used with a base class. Otherwise with both Apple and Banana deriving from Fruit, you could attach a Banana through a WrapperRef<Fruit> even though the original Wrapper<T> was a Wrapper<Apple>…

    Note: this is easy because of the common UnkDisposable base class! This is what gives us a common denominator (WrapperImpl).

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

Need to verify that the attribute can be applied only to a class that
I need to verify that I can use unions a certain way. For C99,
I'm looking for the best way to verify that a given method (the unit)
Within a bash script, what would be the simplest way to verify that a
I need to verify that a method is called, however it receives a parameter
In a bash script I need to verify that the user inputs actual numbers
Is there an easy way to verify that a given private key matches a
I have bunch of action-methods that need to verify the ownership of the orderId
I need a way to store application-level data (i.e. cross user sessions) in ASP.NET.
I need a way for a single variable to represent two kinds of objects

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.