2

I'm attempting to assert following protected class constructors may or may not throw as follows:

#include <utility>
#include <type_traits>

class X
{
protected:
    X() noexcept(false) { }
    X(int) noexcept { }
};

int main()
{
    // should fail
    static_assert(noexcept(std::declval<X>().X()));

    // should pass
    static_assert(noexcept(std::declval<X>().X(3)));

    // will fail regardless of noexcept because constructor is protected,
    // but should pass if default ctor is noexcept and public
    static_assert(std::is_nothrow_constructible_v<X>);

    return 0;
}

static assertion should fail in first case and pass in second.

error is type name is not allowed and I'm not sure what syntax I should use or what would be better approach.

In third static_assert case it will always fail because constructor is not public.

metablaster
  • 1,958
  • 12
  • 26
  • You're not allowed to call constructors. Use a trait for this instead: https://en.cppreference.com/w/cpp/types/is_constructible – NathanOliver Aug 14 '21 at 20:00
  • It will not work for protected constructors, I'll update my post anyway. – metablaster Aug 14 '21 at 20:02
  • 2
    Inherit a dummy class from `X`, then apply the trait to it. Alternatively, change `X` to have protected destructor and public constructors. – HolyBlackCat Aug 14 '21 at 20:09
  • I can't change access level, but inheriting for the purpose of assertion should work. I though there may be more elegant way of doing it. – metablaster Aug 14 '21 at 20:11
  • 1
    What's the point of testing a constructor from a location where you don't have access to it? – Phil1970 Aug 14 '21 at 23:49
  • @Phil1970 static analysis of hierarchy of classes, to quickly detect which classes poison derived classes. I use this in separate test compilation unit. – metablaster Aug 15 '21 at 02:04

0 Answers0