字符串文字作为模板参数
String Literal As Template Argument
c++的这些预处理器和模板限制正在扼杀我。目标是将字符串文字转换为整数。
template<const char* str>
inline int LiteralToInt(){
return __COUNTER__;
}
using std::cout;
int main(){
cout << LiteralToInt<"Hello">();
cout << LiteralToInt<"No">();
cout << LiteralToInt<"Hello">();
return 0;
}
如果模板接受字符串文字,则输出为010。是否有其他方法可以获得此输出并在编译时将字符串文字转换为整数?
是的,C++11的constexpr
将为您完成以下操作:
constexpr int LiteralToInt(const char * str) {
return __COUNTER__; // or whatever.
}
像这样的东西可以在中工作
extern const char HELLO[] = "Hello";
然后
cout << LiteralToInt<HELLO>();
但不是文字本身。这可能不是你想要的。
正如您已经发现的,字符串文字本身不能用作模板参数。
想一想Richard J Ross III使用constexpr的答案,我找到了正确的搜索关键字。。。实际上,您所做的是在编译时对字符串进行哈希处理。您可以在C++11中(但不能在早期版本中)执行此操作,如下所示。
基本想法是使用这样的东西:
unsigned int constexpr const_hash(char const *input) {
// really simple hash function...
return static_cast<unsigned int>(*input)
&& static_cast<unsigned int>(*input) + hash(input+1);
}
但您可能希望使用一个具有比此更健壮属性的哈希函数。。。
然而,如果你没有使用C++11,那么我之前的声明是:
否-在编译时,没有办法将字符串文字转换为整数,即在所有编译单元中,所有相同的字符串都映射到相同的值(不同的字符串映射到不同的值),而不是以某种方式处理代码。
不幸的是,我不知道该怎么做就怎么做。
你可以对字符串设置任何限制吗?喜欢多少个字符?如果你可以将其限制为1-8个字符,你可以这样做:
template <char Ch1, char Ch2 = ' ', char Ch3 = ' ', char Ch4 = ' ', char Ch5 = ' ', char Ch6 = ' ', char Ch7 = ' ', char Ch8 = ' '>
struct string_hash {
static const uint64_t value =
(static_cast<uint64_t>(Ch1) << 56) |
(static_cast<uint64_t>(Ch2) << 48) |
(static_cast<uint64_t>(Ch3) << 40) |
(static_cast<uint64_t>(Ch4) << 32) |
(static_cast<uint64_t>(Ch5) << 24) |
(static_cast<uint64_t>(Ch6) << 16) |
(static_cast<uint64_t>(Ch7) << 8) |
(Ch8);
};
其基本上在编译时将多达8
个字符填充到uint64_t
中。用法如下:
const uint64_t x = string_hash<'T', 'e', 's', 't'>::value
这将创建一个编译时数值(可用于switch
和所有优点),该数值对于1-8个字符长的每个字符串都是唯一的。不幸的是,唯一的缺点是你不能把它写成字符串文字,你需要把它写成char
的列表
相关文章:
- 如何使用字符串文字作为宏参数
- 常量函数,当其参数是对文字类型的引用时
- 为什么带有指针子对象的文字类类型的 constexpr 表达式不能是非类型模板参数
- 函数参数中使用的复杂文字'i'
- 将文字作为const-ref参数传递
- 显式(布尔值)可以作用于字符文字参数的长度吗?
- 为什么对字符串参数的常量引用可以采用字符串文字?
- 使用constexpr验证构造函数中的文字参数
- C++ 当数字文字是参数时,最令人烦恼的解析?
- C++17 类模板参数推导指南和字符串文字
- 用户定义的文字与UINT64_T参数相结合
- 字符串文字扣除模板参数
- 在C++中运行 CMD 行 使用变量(不是字符串文字)作为参数
- 作为预处理器宏参数的多行原始字符串文字
- 字符串文字的模板参数扣除
- _mm_extract_epi8(..) 内部函数,采用非文字整数作为参数
- 当将负文字作为无符号参数传递时,可以g++警告
- 字符串文字作为模板参数
- 模板非类型参数,C++11,对字符串文字的限制
- 以前定义的常量,作为宏参数给出,被认为是字符串文字