Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delay reference to non-nested type based on static condition without compile error?

Consider a header file whose contents are either

namespace foo
{
    static bool const exists = false;
}

or

namespace foo
{
    static bool const exists = true;
    typedef some_other_possibly_incomplete_type my_type;
}

(Assume this header file is given to me as-is and cannot be changed.)

Now consider this typedef:

typedef get_my_type_or_default<foo::exists, void>::type my_type_or_default;

The goal is to have my_type_or_default evaluate to foo::my_type if foo::exists, or void otherwise.

Is it possible to define get_my_type_or_default in a way that makes this work, or is this impossible? If this is possible, how can I do it?

like image 747
user541686 Avatar asked Mar 18 '26 04:03

user541686


1 Answers

Using weird name lookup tricks, unfortunately polluting the global namespace :(

namespace foo
{
    //static bool const exists = true; // we don't need this
    struct some_other_possibly_incomplete_type;
    //typedef some_other_possibly_incomplete_type my_type;
}

using my_type = void;
namespace foo
{
    using this_one_surely_exists = my_type; // either foo::my_type or ::my_type
}


#include <iostream>
template<class T>
void print_type()
{ std::cout << __PRETTY_FUNCTION__ << "\n"; }

int main()
{
    using gey_my_type_or_default = foo::this_one_surely_exists;
    print_type<gey_my_type_or_default>();
}
like image 158
dyp Avatar answered Mar 20 '26 19:03

dyp



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!