C++类型特征,以查看是否可以<uint32_t>对类型"K"的任何变量调用"static_cast(k)"

C++ type trait to see if `static_cast<uint32_t>(k)` can be called on any variable of type `K`

本文关键字:类型 变量 任何 调用 static cast 是否 lt 特征 gt C++      更新时间:2023-10-16

我正在尝试编写一个类型特征来检测,给定类型K,我是否可以在这种类型的变量上调用static_castK(或对K的引用(来uint32_t或不

。这就是我所达到的,但似乎无法使其工作。

template <typename K, typename Whatever = void> struct ConvertibleToUint32 {
static constexpr bool value = false;
};
template <typename K>
struct ConvertibleToUint32<K, decltype(static_cast<uint32_t>(std::declval<K>()))> {
static constexpr bool value = true;
};

我也尝试过使用 std::is_convertible,但似乎在这里不起作用。

这是一个带有运行的粘贴 - https://wandbox.org/permlink/iuP99PNAVIYhh208

专业化似乎没有受到打击。

这是完整的测试程序 -

#include <iostream>
#include <stdint.h>
template <typename K, typename Whatever = void> struct ConvertibleToUint32 {
static constexpr bool value = false;
};
template <typename K>
struct ConvertibleToUint32<K, decltype(static_cast<uint32_t>(std::declval<K>()))> {
static constexpr bool value = true;
};

struct A {
explicit operator uint32_t() const { return 1; }
};
struct B {
};
int main()
{
std::cout << ConvertibleToUint32<A>::value << "n";
std::cout << ConvertibleToUint32<B>::value << "n";
std::cout << std::is_convertible<A, uint32_t>::value << "n";
}

它不会被击中,因为decltype(static_cast<uint32_t>(std::declval<K>()))不是void,所以它不是参数Whatever=void的主模板的更专业版本。

修复相当容易

template <typename K>
struct ConvertibleToUint32<K, decltype(static_cast<uint32_t>(std::declval<K>()), void())> {
static constexpr bool value = true;
};

第二个参数与默认值匹配,因此将按部分顺序选取。或者,您可以只指定默认值Whatever=uint32_t并获得相同的效果。void只是一般成语所采用的。

template <typename K, typename Whatever = uint32_t>
struct ConvertibleToUint32 {
static constexpr bool value = false;
};

顺便说一句,我建议您开始偏爱cstdint标头及其std::uint32_t别名。通常具有相同的净效果,但通常最好使用C++版本。