Search code examples
c++templatestypedeftemplate-meta-programmingconditional-compilation

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?


Solution

  • 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>();
    }