Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

has_type template returns true for struct type {};

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 *.

?

like image 389
tony Avatar asked Sep 02 '14 14:09

tony


People also ask

Which of the following is a true statement about templates?

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.

How do I restrict a template type in C++?

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.

What is the difference between Typename and class in template?

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.

How many types of templates are there in C ++?

Technical overview. There are three kinds of templates: function templates, class templates and, since C++14, variable templates.


1 Answers

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.

like image 199
Alan Stokes Avatar answered Oct 12 '22 01:10

Alan Stokes