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`
我正在尝试编写一个类型特征来检测,给定类型K
,我是否可以在这种类型的变量上调用static_cast
K
(或对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++版本。
相关文章:
- 从模板创建通用打印函数,以打印基元数据类型变量的值
- 指针数据类型变量如何包含对象?
- 将 static_cast<int>(-15) 分配给静态常量字符类型变量
- 将内置类型变量传递给只有一个类类型参数的"+"运算符函数时自动类型转换的构造函数
- 如何为结构类型变量赋值
- 如何将字符类型变量附加到字符串中?
- 共享或私有 openmp 代码中的结构化类型变量
- 有没有办法在 c++ 中制作类型变量?
- 从其他类声明类类型变量会给出 C2143 错误(在"*"之前缺少";")
- 如何检查类中定义的枚举类型变量是否被分配给?
- 将子类实例保存在父类型变量中并通过父变量使用 Child 函数?
- 是否可以在没有结构的情况下创建新的类型变量?
- 为什么类型变量;不调用默认 CTR
- 如何使用CIN将输入整数值获取到char类型变量中
- 如何为 char** 类型变量提供适当的值,以便将其分配给字符串变量
- 在C++标准中哪里说必须初始化 const 内置类型变量的定义
- 为什么可以将其他类型变量用作C 中常量参考参数参数的参数
- Eclipse CDT 打开声明的自动类型变量
- 如何计算长长类型变量中的位数
- 将自动类型变量初始化为零.这种类型安全吗?