【发布时间】:2021-06-09 05:53:42
【问题描述】:
为什么以下代码无法编译?为具有特定成员的类型启用模板最简洁的解决方案是什么?如果模板变量被直接用于初始化它的表达式替换,它也会编译。
#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;
}
【问题讨论】:
-
请在问题中包含编译器错误