Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
200 views
in Technique[技术] by (71.8m points)

c++ - Different template syntax for finding if argument is a class or not

While reading this question , I came across @Johannes's answer.

template<typename> struct void_ { typedef void type; };

template<typename T, typename = void>  // Line 1
struct is_class { static bool const value = false; };

template<typename T>
struct is_class<T, typename void_<int T::*>::type> { // Line 2
  static bool const value = true; 
};

This construct finds if the given type is a class or not. What puzzles me is the new kind of syntax for writing this small meta program. Can anyone explain in detail:

  1. Why we need Line 1 ?
  2. What is the meaning of syntax <int T::*> as template parameter in Line 2 ?
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Line 1: Choosing the partial specialization below if the test succeeds.

Line 2: int T::* is only valid if T is a class type, as it denotes a member pointer.

As such, if it is valid, void_<T>::type yields void, having this partial specialization chosen for the instantiation with a value of true. If T is not of class type, then this partial specialization is out of the picture thanks to SFINAE and it defaults back to the general template with a value of false.

Everytime you see a T::SOMETHING, if SOMETHING isn't present, be it a type, a data member or a simple pointer definition, you got SFINAE going.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...