EN VI

C++ - How can I statically assert that two fields in different third-party libraries are the same?

2024-03-11 19:00:04
C++ - How can I statically assert that two fields in different third-party libraries are the same?

If I have something like:

// library 1:

struct A
{
    struct B
    {
        std::map<std::string, int> LookupTable;
    };

    B b;
};

// library 2:
struct C
{
    std::map<std::string, int> LookupTable;
};

How could one write something akin to the following, but that actually works?

// 1
static_assert(typeof(A::B::LookupTable) == typeof(C::LookupTable));

// 2
static_assert(typeof(A::B::LookupTable) == typeof(map<std::string, int>));

// 3
A a;
static_assert(typeof(a.x) == typeof(map<std::string, int>));

The typeof and typeid operators obviously don't suit the problem.

Solution:

Use decltype instead of typeof, and std::is_same_v instead of ==:

static_assert(std::is_same_v<decltype(A::B::LookupTable), decltype(C::LookupTable)>);
static_assert(std::is_same_v<decltype(C::LookupTable), std::map<std::string, int>>);

Demo

Answer

Login


Forgot Your Password?

Create Account


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

Reset Password

Back to login