gpt4 book ai didi

c++ - 没有特定成员的类型的 SFINAE

转载 作者:行者123 更新时间:2023-12-04 02:27:17 28 4
gpt4 key购买 nike

为什么以下代码无法编译?为具有特定成员的类型启用模板的最简洁的解决方案是什么?如果模板变量被直接用于初始化它的表达式替换,它也会编译。

#include <iostream>

template<class T>
constexpr bool is_rect = std::is_same_v<decltype(T::left, T::top, T::right, T::bottom, void()), void>;

// compiles if is_rect<T> is replaced with the expression directly, but of course it's not a solution
template<class T, std::enable_if_t<is_rect<T>, int> = 0>
void f(T)
{
std::cout << "rect enabled\n";
}

template<class T, std::enable_if_t<std::is_arithmetic_v<T>, int> = 0>
void f(T)
{
std::cout << "arithmetic enabled\n";
}

struct ActualType { float left, top, right, bottom; };

int main()
{
f(ActualType{});
f(int{});
return 0;
}

最佳答案

问题是 is_rect<T>始终指定为 std::enable_if_t 的模板参数作为 f() 签名的一部分, 当 T 时为无效表达式没有特定的成员。

您可以应用部分特化来制作 is_rect给出 truefalse基于类型是否具有特定成员。例如

template<class T, class = void>
constexpr bool is_rect = false;
template<class T>
constexpr bool is_rect<T, std::void_t<decltype(T::left, T::top, T::right, T::bottom)>> = true;

然后

template<class T, std::enable_if_t<is_rect<T>, int> = 0>
void f(T)
{
std::cout << "rect enabled\n";
}

LIVE

关于c++ - 没有特定成员的类型的 SFINAE,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66579140/

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