How to distinguish function type with SFINAE

I am reading C ++ Templates books. He mentions SFINAE (replacement failure is not an error). The principle of operation can be used to determine the type of function. Code example:

template <typename T>
class IsFunctionT {
private:
   typedef char One;
   typedef struct { char a[2]; } Two;
   template<typename U> static One test(...);
   template<typename U> static Two test(U (*)[1]); // This test overloading I cannot understand 
public:
   enum { Yes = sizeof(IsFunctionT<T>::test<T>(0) == 1};
   enum { No = !Yes };
};

I understand that his goal is to find functions that cannot be classified as arrays, but how it works with U (*)[1]. I've never seen this before.

+4
source share
2 answers

U () [1] is an unnamed pointer to an array of 1 element. And 0 is either considered int, or a null pointer to U () [1];

sizeof checks the type of the return value of the function, the actual result of the test function is not used, since test () is never called, and only its return type is checked.

0

, SFINAE , , . , , , U - , . , , , , . , ..

template<typename T>
class IsFunctionT<T&> {
  public:
    enum { Yes = 0 };
    enum { No = !Yes };
};

template<>
class IsFunctionT<void> {
  public:
    enum { Yes = 0 };
    enum { No = !Yes };
};

template<>
class IsFunctionT<void const> {
  public:
    enum { Yes = 0 };
    enum { No = !Yes };
};

.

0

Source: https://habr.com/ru/post/1691547/


All Articles