There are a number of ways to implement a has_type<T>
template that deduces if T
has a nested class or typedef named type
. ie
namespace detail {
template<typename> struct tovoid { typedef void type; };
}
template<typename T, typename = void> struct has_type
: std::false_type { };
// this one will only be selected if C::type is valid
template<typename C> struct has_type<C, typename detail::tovoid<typename C::type>::type>
: std::true_type { };
Or
template <typename C> char test_for_type(...) { return '0'; }
template <typename C> double test_for_type(typename C::type const *) { return 0.0; }
template <typename T> struct has_type
{
static const bool value = sizeof(test_for_type<T>(0)) == sizeof(double);
};
however in either case, has_type<type>::value
is true
for this class:
struct type
{
};
Now the above type
doesn't have another type
nested within it, but it does have a constructor type::type()
.
But should that constructor 'trigger' the checks for the nested type? Or is it a compiler bug?
(I would like to think that typename type::type
didn't apply to a constructor and/or that you couldn't take a pointer to a constructor, such as what would be produced by the second test method: typename type::type const *
.
?
Which of the following is correct about templates? Explanation: Templates are used for generic programming hence allowing to write a single function for all data types. It is a type of compile time polymorphism.
There are ways to restrict the types you can use inside a template you write by using specific typedefs inside your template. This will ensure that the compilation of the template specialisation for a type that does not include that particular typedef will fail, so you can selectively support/not support certain types.
There is no semantic difference between class and typename in a template-parameter. typename however is possible in another context when using templates - to hint at the compiler that you are referring to a dependent type. §14.6.
Technical overview. There are three kinds of templates: function templates, class templates and, since C++14, variable templates.
The name of a class is "injected" into the scope of the class, so type::type
really is the name of a type, and it's the same type as ::type
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With