Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Attempt to understand how void_t described by Walter Brown works
#include <type_traits>
#include <iostream>
using namespace std;
template< class... > struct voider { using type = void; };
template< class... T0toN > using void_t = typename voider<T0toN...>::type;
// does NOT work
/*
template< class, class = int >
struct has_type_member : false_type { };
*/
// works (note void matches void_t)
template< class, class = void >
struct has_type_member : false_type { };
template< class T >
struct has_type_member<T, void_t<typename T::type>> : true_type { };
// should not match (not a "type")
struct foo {
int type;
};
// should not match (not there at all)
struct bar {};
// should match ("type" is there, and it is a type)
struct baz {
typedef int type;
};
int main() {
if (has_type_member<foo>::value) {
std::cout << "foo has a type member\n";
} else {
std::cout << "foo does not have a type member\n";
}
if (has_type_member<bar>::value) {
std::cout << "bar has a type member\n";
} else {
std::cout << "bar does not have a type member\n";
}
if (has_type_member<baz>::value) {
std::cout << "baz has a type member\n";
} else {
std::cout << "baz does not have a type member\n";
}
}
@jefftrull
Copy link
Author

jefftrull commented Sep 17, 2014

So my question is why the default int version of has_type_member does not work, while the default void version does. Why is the default int version preferred over the void_t specialization, while the default void version is not?

@jefftrull
Copy link
Author

jefftrull commented Sep 18, 2014

For the record, the answer appears to be that the first definition of has_type_member is the "primary template" whose default applies to any instantiation that does not specify the type of the second template argument. So in main, these calls look to the compiler as though we had written:

has_type_member<foo, void>

The specialization will match and be chosen if its second argument evaluates to void. So when I replace the default argument in the primary template with "int", the specialization cannot match.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment