0

I read a code snippet just now:

    template<class T>
    struct HasHelloWorld
    {
        typedef char(&yes)[1];
        typedef char(&no)[2];

        template <typename C> static yes check(decltype(&C::HelloWorld));
        template <typename> static no check(...);

        static constexpr bool value = sizeof(check<T>(0)) == sizeof(yes);
    };

Is this because when sizeof accepts an evaluation, the evaluation doesn't get calculated?

Lucas
  • 222
  • 3
  • 9
  • 4
    _"...When applied to an expression, sizeof __does not__ evaluate the expression, ..."_ https://en.cppreference.com/w/cpp/language/sizeof – Richard Critten Apr 07 '22 at 12:52
  • 1
    consider what you need to know to determine the sizeof the value returned from the call `check(0)`, then consider if you need to know the definition of the function. No, all you need to know is the return type after overload resolution, but actually calling the function is not necessary – 463035818_is_not_an_ai Apr 07 '22 at 12:54
  • @463035818_is_not_a_number that makes sense. – Lucas Apr 07 '22 at 12:55
  • though such handwaving and relying on common sense doesnt always work with C++, unfortunately ;) – 463035818_is_not_an_ai Apr 07 '22 at 12:56
  • 1
    note that the code you posted is rather old-fashioned. C++11 introduced a couple of helpers to make such stuff simpler and C++20 introduced a whole new concept of concepts to achieve the same with less arcance code – 463035818_is_not_an_ai Apr 07 '22 at 13:00
  • @463035818_is_not_a_number could u give me a hint about the modern C++ ways to do this? – Lucas Apr 07 '22 at 13:09
  • here you can find a lot of different ways, pre-C++11, C++11 and if you scroll down enough also C++20 https://stackoverflow.com/questions/87372/check-if-a-class-has-a-member-function-of-a-given-signature (though it is for a method of fixed signature) – 463035818_is_not_an_ai Apr 07 '22 at 13:13

0 Answers0