在编译时将类型转换为整数
Convert a type to an integer at compile-time?
在C 中是否有办法将类型转换为Compile-time(也许使用TypeID)的整数?我的目标是通过该类中的每种类型传递唯一代码:
template<int TypeCode>
class MyClass
{
};
编辑:有关我要做的事情的更多详细信息。实际上,myclass会更像:
template<int Code>
class AbstractBase
{
};
我用大量的CRTP技术编写了一个高度的模板代码,我需要检查某些操作之间的兼容性代码。为此,我的想法是从抽象库类中继承兼容类型,为所有这些类型指定相同的代码。使用此操作,只需调用std::enable_if<std::is_base_of<AbstractBase<MyCode>, T>::value>::type
,我就可以检查某些操作的类型兼容性。
一阶,我可以手工生成一个代码,但是如果我可以自动从类型生成此代码,它将更加优雅。
有很多方法。这是模板专业化:
#include<iostream>
using namespace std;
template<class T> struct type_code { enum{value=0}; }; // unknown type code
template<> struct type_code <int> { enum{value=1}; };
template<> struct type_code <float>{ enum{value=2}; };
int main() {
cout << type_code<void>::value << endl;
cout << type_code<int>::value << endl;
cout << type_code<float>::value << endl;
}
输出:
0
1
2
不确定我是否完全了解您。这是你在说什么吗?
template<int TypeCode>
class MyClass
{
private:
int i;
double d;
public:
template<typename T>
operator T()
{
if(strcmp(typeid(T).name(),"int")==0)
return i;
else if(strcmp(typeid(T).name(),"double")==0)
return d;
// some other types here ...
}
};
好吧,您可以创建一个类型列表,然后在编译时提取该列表中的类型索引。
从我的另一个答案中,这是这种技术:
#include <type_traits>
template<typename... Types>
struct Seq {};
template<typename T, typename Seq, typename=void>
struct IndexOf;
template<typename T, typename First, typename... Types>
struct IndexOf<T, Seq<First, Types...>, typename std::enable_if< std::is_same<T, First>::value >::type > {
enum { value = 0 };
};
template<typename T, typename First, typename... Types>
struct IndexOf<T, Seq<First, Types...>, typename std::enable_if< !std::is_same<T, First>::value >::type > {
enum { value = 1+IndexOf<T,Seq<Types...>>::value };
};
typedef Seq< bool, char, unsigned char, short, unsigned short, int, unsigned int, long, unsigned long > IntegerTypes;
#include <iostream>
int main() {
std::cout << IndexOf< int, IntegerTypes >::value << "n";
// this next line will not compile, because void is not in the IntegerTypes sequence:
// std::cout << IndexOf< void, IntegerTypes >::value << "n";
}
我在整数上使用它。
因此,如果您有要整数的类型列表,则可以列出所有类型,上述技术将为每个类型提供一个独特的整数(反向映射也相对容易 - 编译时间索引到列表类型)。
相关文章:
- 有关插入适配器的错误。[错误]请求从 'back_insert_iterator<vector<>>' 类型转换为非标量类型
- 整数类型应该显式转换(例如"int"到"无符号")还是只会增加混乱?
- 有没有办法将字符类型转换为整数?
- 类型转换问题:返回为整数而不是浮点/类型
- 将字符串转换为整数类型T,检查是否存在溢出
- 整数在 C++ 中没有被类型转换为布尔值
- 如何处理警告:从较小的整数类型int转换为int*
- 在编译时将类型转换为整数
- 如何在 python 中将无符号字符类型的整数字符串转换为整数
- 类型转换问题:字符数组的元素转换为整数变量
- 将枚举类型转换为整数,反之亦然
- 将浮点数 32 位变量类型转换为无符号整数 32 位时进行了哪些位级更改
- 如何让 VS2013 停止生成对整数类型之间强制转换的__dtol3、__dtoui3和其他函数的调用
- 如何将字节数组转换为整数类型(整数、长整型、短型等)"安眠安"?
- 为什么将整数文本类型转换为指针值会导致非常量表达式
- 类型转换并将 void 指针变量分配给 VC++ 中的整数变量
- boost序列化错误C4308:负整数常量转换为无符号类型
- 如何安全地将更宽的整数类型转换为位域
- int8_t 和 char:在指针之间转换为具有不同符号的整数类型 - 但它不会
- 如何防止使用多种整数类型的boost::变体类型的隐式转换