The task is to check that type T function of a certain type. We use a class of restrictions. Due to inheritance, a constructor is called. I don’t understand how it calls a static function to get (if everything is bad) an error in a line specifying an address to a function pointer. In the same way, it seems that simply assigning the address of this function to the pointer.

 template<typename T> class Has_f { public: static void Constraints() { T* (T::*test)() const = &T::f; test; } Has_f() { void (*p)() = Constraints; } }; 

Our class:

 template <typename T> class C : Has_f<T> { // ... }; 

Why did the author write this way? You can just call in the constructor {Constraints();} or not? The fragment is taken from the book of G. Sutter.

  • There is no challenge in the constructor - HasmikGaryaka
  • one
    And from which book? I think he explains everything there. - HasmikGaryaka
  • Solving complex problems in C ++. This moment is not explained. What is the essence of the class of restrictions - I understood how to use too. I do not quite understand such a call by the constructor of the stat function. And in general, why not to transfer her body to the Has_f constructor? - Jenssen

1 answer 1

You can call. But why?

All checks are purely static, not giving any executable code, i.e. no runtime overhead .

Update
I have an option in C ++ 11 to make it simpler:

 template<typename T, typename = enable_if_t<is_same<decltype(&T::f), // Имя функции-члена T* (T::*)()>::value>> // Ее тип, что нам нужен class C ... 

Well, or even more fun:

 static_assert(is_same<decltype(&T::f),T* (T::*)(int)>::value,"Error"); 

Standards guru, what do you say? ...

  • And how does it (test) work? Here we called constructor Has_f, what next? We do not apply to Constraints. - Jenssen
  • There is actually an extra Constraints() . The main thing is that we should get the address &T::f . And if we are unable to get it (there is no such function, inconsistency of the signature), we will get a compilation error. - Harry
  • So, is it true that I understand that you can safely put a line to get this address in k and remove the Constraints? I do not quite understand why the author promoted a similar model in the book. - Jenssen
  • As for me - yes, you can. But maybe some special standards gurus will find some tricky case when this is wrong? ... - Harry
  • Well, I'm not a guru yet, I will do it in a simple way. - Jenssen