SFINAE 和衰变不能一起工作。为什么?
SFINAE and decay don't work together. Why?
我正在学习 C++ 元编程。我想根据传递的类型自动检测 opengl 类型 id。我的代码通过了 decltype(array)
,变成了 float*
。如果我使用 GLType<float>::type
它工作正常,但 GLType<float*>::type
失败并出现“未知成员类型”错误。我认为 std::is_same_v<std::decay_t<T>, float>>
将在任何 float*, float[], const float, etc..
上评估为 true_type
,如 here
所述
template <typename T, typename = void>
struct GLType {};
template <typename T>
struct GLType<T, std::enable_if_t<std::is_same_v<std::decay_t<T>, float>>> {
const static constexpr int type = GL_FLOAT;
};
template <typename T>
struct GLType<T, std::enable_if_t<std::is_same_v<std::decay_t<T>, double>>> {
const static constexpr int type = GL_DOUBLE;
};
std::decay_t
不会从类型中删除指针。如果你想这样做,你需要使用 std::remove_pointer_t
,像这样:
template <typename T>
struct GLType<T, std::enable_if_t<std::is_same_v<std::remove_pointer_t<std::decay_t<T>>, float>>> {
// ^^^^^^^^^^^^^^^^^^^^^ add this
const static constexpr int type = GL_FLOAT;
};
另一个模板也类似。
我正在学习 C++ 元编程。我想根据传递的类型自动检测 opengl 类型 id。我的代码通过了 decltype(array)
,变成了 float*
。如果我使用 GLType<float>::type
它工作正常,但 GLType<float*>::type
失败并出现“未知成员类型”错误。我认为 std::is_same_v<std::decay_t<T>, float>>
将在任何 float*, float[], const float, etc..
上评估为 true_type
,如 here
template <typename T, typename = void>
struct GLType {};
template <typename T>
struct GLType<T, std::enable_if_t<std::is_same_v<std::decay_t<T>, float>>> {
const static constexpr int type = GL_FLOAT;
};
template <typename T>
struct GLType<T, std::enable_if_t<std::is_same_v<std::decay_t<T>, double>>> {
const static constexpr int type = GL_DOUBLE;
};
std::decay_t
不会从类型中删除指针。如果你想这样做,你需要使用 std::remove_pointer_t
,像这样:
template <typename T>
struct GLType<T, std::enable_if_t<std::is_same_v<std::remove_pointer_t<std::decay_t<T>>, float>>> {
// ^^^^^^^^^^^^^^^^^^^^^ add this
const static constexpr int type = GL_FLOAT;
};
另一个模板也类似。