所以,我希望能够进行静态常量编译
时间结构,它通过使用基于字符串保存一些值
模板。我最多只想要四个字符。我知道
'abcd' 的类型是 int
, 'ab','abc' 也是,虽然
'a' 的类型为 char
, 它适用于 template<int v> struct
我想做的是将一些 const char "abcd"的大小设为 2,3,4,5 并且具有与使用“abcd”相同的功能。 请注意 我不是指 1、2、3 或 4,因为我期望空终止符。
cout << typeid("abcd").name() << endl;
告诉我的类型
这个硬编码字符串是 char const [5]
,其中包括空
最后的终结者。
我知道我需要将这些值作为字符来处理, 所以它们被表示为一个整数。
我不能使用 constexpr
因为 VS10 不支持它(VS11 也不支持..)
因此,例如在某个地方定义了这个模板,然后是最后一行
template <int v> struct something {
static const int value = v;
};
//Eventually in some method
cout << typeid(something<'abcd'>::value).name() << endl;
工作得很好。
我试过了
template<char v[5]> struct something2 {
static const int value = v[0];
}
template<char const v[5]> struct something2 {
static const int value = v[0];
}
template<const char v[5]> struct something2 {
static const int value = v[0];
}
所有这些都是单独构建的,尽管当我进行测试时,
cout << typeid(something2<"abcd">::value).name() << endl;
我明白了
'something2' : invalid expression as a template argument for 'v'
'something2' : use of class template requires template argument list
这是不可行的还是我误解了什么?
最佳答案
14.1 列出了可接受的非类型模板参数类型:
— integral or enumeration type,
— pointer to object or pointer to function,
— lvalue reference to object or lvalue reference to function,
— pointer to member,
数组不属于这些类别中的任何一个。
14.3.2/1 列出了允许作为模板参数的类别,14.3.2/2 继续说:
Note: A string literal (2.14.5) does not satisfy the requirements of any of these categories and thus is not an acceptable template-argument.
因此你不能做你想做的事。
关于C++ 模板 const char 数组到 int,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12717174/