SFINAE示例不清楚
SFINAE example not clear
http://en.wikipedia.org/wiki/Substitution_failure_is_not_an_error
#include <iostream>
template <typename T>
struct has_typedef_foobar {
// Types "yes" and "no" are guaranteed to have different sizes,
// specifically sizeof(yes) == 1 and sizeof(no) == 2.
typedef char yes[1];
typedef char no[2];
template <typename C>
static yes& test(typename C::foobar*);
template <typename>
static no& test(...);
// If the "sizeof" the result of calling test<T>(0) would be equal to the sizeof(yes),
// the first overload worked and T has a nested type named foobar.
static const bool value = sizeof(test<T>(0)) == sizeof(yes);
};
struct foo {
typedef float foobar;
};
int main() {
std::cout << std::boolalpha;
std::cout << has_typedef_foobar<int>::value << std::endl;
std::cout << has_typedef_foobar<foo>::value << std::endl;
}
上例显示了SFAINE。
- 这里我不明白为什么sizeof(yes(==1和sizeof(no(==2
- 由于测试是静态功能,因此应该有一些测试函数的定义。但这里的代码编译良好没有定义测试功能
1(sizeof(char)
被定义为等于1。由于yes
是一个由一个字符组成的数组的typedef,所以它的大小必须是一。同样,由于no
是一个由两个字符组成的数组的typedef,所以它的大小必须是2 * sizeof(char)
,也就是2。
2( 函数test
从未被调用,因此定义是不必要的-sizeof
运算符是一个编译时操作,因此编译器只查看具有指定模板参数的测试实例化的返回类型的大小。因为它没有被调用,所以定义是不必要的,类似于为了使类不可复制而使私有的未定义副本构造函数。
相关文章:
- 关于隐式声明的复制构造函数的引用在逻辑上不清楚
- C++复制 c'tor 现在确实会采取行动。 不清楚为什么
- 矢量编程:不清楚矢量的初始化
- 调用虚函数的逻辑不清楚(或者是方法隐藏?
- cudaMemcpy 在从设备读取到主机时返回 cudaErrorInvalidArgument,不清楚原因
- 实现附加对象:不清楚的文档示例
- 智能指针移动语义我不清楚
- 在 c++ 中移动 2d 数组的构造函数(语法逻辑不清楚):
- 为什么这个错误如此不清楚
- 在特定情况下,指针删除和铸造之间的关系不清楚
- 切换语句在 C++ 中的输出不清楚
- 为什么我在这里不需要Sfinae
- 不清楚的副本分配操作员示例
- 我在c++应用程序上搞不清楚
- Visual Studio 2012 中的错误日志不清楚
- C++引用-有些事情我不清楚
- 解密不清楚的语法
- 使用Boost Coroutine(1.55)的不清楚分割错误
- 不清楚按位 AND 赋值的使用
- SFINAE示例不清楚