gpt4 book ai didi

C++ void_t SFINAE false_type true_type 无法获得特化

转载 作者:行者123 更新时间:2023-12-01 14:04:16 25 4
gpt4 key购买 nike

一切看起来都很简单。

在我下面的代码中,对于 T=vector,has_member_type::value 不应该为真吗?对不起,如果它已经被回答了。我找了一会儿,但找不到答案。

#include <iostream>
#include <type_traits>

// has_value_type
template <typename, typename = std::void_t<>>
struct has_value_type: std::false_type {};

template <typename T>
struct has_value_type<T, std::void_t<typename T::value_type>>: std::true_type {};

int main()
{
std::cout << "bool: " << std::boolalpha << has_value_type<bool>::value << std::endl;
std::cout << "vector_has: " << std::boolalpha << has_value_type<std::vector<int>>::value << std::endl;

std::cout << "true_type: " << std::boolalpha << std::true_type::value << std::endl;
std::cout << "false_type: " << std::boolalpha << std::false_type::value << std::endl;
return 0;
}

输出:

bool: false
vector_has: false
true_type: true
false_type: false

我正在使用 clang++

clang version 9.0.0 (tags/RELEASE_900/final)
Target: x86_64-apple-darwin17.7.0
Thread model: posix

最佳答案

如果您使用 libc++标准库实现,不包括 <vector> ,然后是 std::vector 的前向声明介绍:

#include <iostream> // forward declares std::vector

demo

此前向声明允许代码编译,但 sfinae 检查返回 false因为没有为 std::vector 定义成员类型还没有。

你不能依赖这个,应该总是#include<vector>如果你想使用 std::vector在任何情况下。

关于C++ void_t SFINAE false_type true_type 无法获得特化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63289122/

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