gpt4 book ai didi

c++ - SFINAE 示例不清楚

转载 作者:太空狗 更新时间:2023-10-29 21:02:59 26 4
gpt4 key购买 nike

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 和大小(无)==2。
  • 因为测试是静态函数,所以应该有一些测试函数的定义也。但是这里的代码编译得很好没有定义测试函数

最佳答案

1) sizeof(char) 被定义为等于 1。因为 yes 是一个字符数组的类型定义,它的大小必须是 1。同样,由于 no 是两个字符数组的 typedef,它的大小必须是 2 * sizeof(char),即 2。

2) 函数test 永远不会被调用,所以定义是不必要的 - sizeof 运算符是一个编译时操作,所以编译器只看大小具有指定模板参数的测试实例化的返回类型。因为它不被调用,所以定义是不必要的,类似于为了使类不可复制构造而创建私有(private)非定义复制构造函数。

关于c++ - SFINAE 示例不清楚,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14210678/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com