3

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?

4
  • @dyp: I can't modify the header, so if you can do that without modifying the header then sure. Otherwise no.
    – user541686
    Aug 1, 2014 at 21:17
  • @dyp: Oh, I misunderstood what you meant. That's a good point. The problem is the typedef is not necessarily a complete type, even though I made the mistake of making it so in my example (edit: I fixed it to show what I mean).
    – user541686
    Aug 1, 2014 at 21:18
  • @dyp: Well I don't know what its name might be, so I wouldn't know how to refer to it.
    – user541686
    Aug 1, 2014 at 21:24
  • @dyp: Ahh! That's a brilliant answer, please post it!! :)
    – user541686
    Aug 1, 2014 at 21:30

1 Answer 1

4

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>();
}
3
  • I think you can even prevent pollution of the global namespace -- use using foo; inside some other detail namespace, and define my_type to be void inside detail. :)
    – user541686
    Aug 1, 2014 at 21:34
  • @Mehrdad If you mean using namespace foo;, then I don't think that will work: using-directives behave weirdly, they introduce the names in the smallest enclosing scope that contains the current and the referred namespace (which will be either foo or the global namespace).
    – dyp
    Aug 1, 2014 at 21:35
  • Oh wow, that's really bizarre, I didn't realize that. :( bummer.
    – user541686
    Aug 1, 2014 at 21:42

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.