[英]how to distinguish function type with SFINAE
I'm reading book C++ Templates . 我正在读书C ++模板 。 It mentions SFINAE(substitution failure is not an error) principal can be used to detect function type.
它提到SFINAE(替换失败不是错误)主体可用于检测函数类型。 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 its intent is to find functions which cannot be categorized as arrays, but how does it work with U (*)[1]
. 我理解它的目的是找到不能归类为数组的函数,但它如何与
U (*)[1]
。 I have never seen this before. 我以前从未见过这个。
The U( )[1] is an unnamed pointer to an array of 1 element. U( )[1]是一个指向1个元素数组的未命名指针。 And the 0 is either treated as an int or a null pointer to an U ( )[1];
并且0被视为指向U( )[1] 的int或null指针 ;
The sizeof is testing the function return type, the actual result of the test function isn't used as test() is never actually called, only its return type tested. sizeof是测试函数返回类型,测试函数的实际结果不用作test()从不实际调用,只测试其返回类型。
In a nutshell, SFINAE works by substituting a type and not giving a hard failure if the expression is ill-formed. 简而言之,如果表达形式不正确,SFINAE通过替换一种类型而不是硬性失败来工作。 For example you cannot have an array of functions, so if
U
is a function, the substitution will fail and that overload will be discarded. 例如,您不能拥有一个函数数组,因此如果
U
是一个函数,则替换将失败并且该重载将被丢弃。 Now as a comment pointed out, the code you posted alone does not cover all cases. 现在正如评论所指出的那样,您单独发布的代码并未涵盖所有案例。 You need additional specializations, ie:
您需要其他专业化,即:
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 };
};
Which I pulled from the freely available source code from the book . 我从书中免费提供的源代码中提取 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.