【发布时间】:2020-05-01 14:22:13
【问题描述】:
我正在尝试编写一个根据类自身模板参数的值公开不同构造函数的类。尝试执行此操作时想到的幼稚代码如下:
// C++14
#include <type_traits>
template <int compile_time_w = -1, int compile_time_h = -1>
struct Grid
{
template <std::enable_if_t<compile_time_w < 0 && compile_time_h < 0, int> = 0>
Grid(int runtime_w, int runtime_h) : _w(runtime_w), _h(runtime_h) {}
template <std::enable_if_t<compile_time_w < 0 && compile_time_h >= 0, int> = 0>
Grid(int runtime_w) : _w(runtime_w), _h(compile_time_h) {}
template <std::enable_if_t<compile_time_w >= 0 && compile_time_h < 0, int> = 0>
Grid(int runtime_h) : _w(compile_time_w), _h(runtime_h) {}
template <std::enable_if_t<compile_time_w >= 0 && compile_time_h >= 0, int> = 0>
Grid() : _w(compile_time_w), _h(compile_time_h) {}
int _w, _h;
};
int main()
{
// Grid<2, 2> grid; // any combination of template parameters + constructor parameters fails to compile
return 0;
}
编译类而不对其进行任何实例化可以正常工作,但尝试以任何方式或容量实例化它总是失败。编译错误的格式总是相同的,并且会为每个 SFINAE 应该触发的构造函数报告:
error: no type named ‘type’ in ‘struct std::enable_if’
显然std::enable_if 正在按预期工作,但不知何故不应将其视为错误。关于这一切的任何线索?
【问题讨论】:
-
类模板参数不是模板构造函数的直接上下文的一部分,因此 SFINAE 不适用。
-
解释下提到了here。