C++ void_t SFINAE false_type true_type 无法获得专业化

3 c++ templates sfinae void-t

这一切看起来很简单。

在我下面的代码中,对于 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;
}
Run Code Online (Sandbox Code Playgroud)

输出:

bool: false
vector_has: false
true_type: true
false_type: false
Run Code Online (Sandbox Code Playgroud)

我正在使用 clang++

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

cig*_*ien 5

如果您使用libc++标准库实现,并且不包含<vector>,则std::vector引入的前向声明为:

#include <iostream> // forward declares std::vector
Run Code Online (Sandbox Code Playgroud)

演示

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

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