[英]Why does std::is_literal_type<std::String> == false and how can I get around it?
I'm currently trying to use constexpr
to define some input identification stuff: 我目前正在尝试使用
constexpr
定义一些输入标识的东西:
struct RangeParams {
string legacyId;
string fullname;
string shortname;
float min = -1;
float baseline = 0;
float max = 1;
float defaultValue = 0;
};
...
inline constexpr RangeParams curve1 = { "some_id", "my_name", ...};
Unfortunately, I get an error for the constexpr line saying 不幸的是,我对constexpr行说了一个错误
Constexpr variable cannot have non-literal type 'const RangeParams'
Constexpr变量不能具有非文字类型“ const RangeParams”
So, I dug into it to figure out what part of this is non-literal, and string
was the culprit. 因此,我仔细研究了其中的哪些部分是非文字的,而
string
是罪魁祸首。
std::cout << std::is_literal_type<float>::value; // output: 1
std::cout << std::is_literal_type<string>::value; // output: 0
Finding this has highlighted an important fact for me which is that my understanding of literal-types is rather flawed. 找到这一点对我来说是一个重要的事实,那就是我对文字类型的理解相当有缺陷。 For the most part, I'd simply thought of them as being the basics (numbers, strings, booleans, structs made of those things).
在大多数情况下,我只是将它们视为基本知识(数字,字符串,布尔值,由这些东西组成的结构)。
So why would a simple string not be a literal type? 那么,为什么简单的字符串不是文字类型呢? What's the gotcha here?
这是什么陷阱?
Also, how can I get around this? 另外,我该如何解决? I'm trying to make a global out of my RangeParams and the most modern answer to this question ( Defining global constant in C++ ) appears not be working.
我试图从我的RangeParams中创建一个全局变量,并且这个问题的最现代答案( 在C ++中定义全局常量 )似乎无法正常工作。
std::string
is not a literal. std::string
不是文字。 const char[]
is. const char[]
是。 The gotcha is that a std::string
is a container of a dynamic size. 问题是
std::string
是动态大小的容器。 No, you can't get around this and still use std::string
. 不,您无法绕开它,仍然使用
std::string
。 std::string
is unusable in constexpr context. std::string
在constexpr上下文中不可用。
You might want to replace std::string
with const char*
in your code: 您可能需要在代码中用
const char*
替换std::string
:
struct RangeParams {
const char* legacyId;
const char* fullname;
const char* shortname;
float min = -1;
float baseline = 0;
float max = 1;
float defaultValue = 0;
};
It's not exactly the same, but given the lack of context, it's hard to justify what did you exactly need the std::string
for, thus it's uncertain that a const char*
will be a suitable alternative. 它并不完全相同,但是由于缺乏上下文,很难证明您确实需要
std::string
的原因,因此不确定const char*
将是合适的选择。
EDIT: A short example should help to understand the misconception. 编辑:一个简短的例子应该有助于理解误解。 What is the type of
0
?. 0
是什么类型? It's an int
. 这是一个
int
。 What's the type of 'a'
? 什么是
'a'
类型? It's a char
. 这是一个
char
。 What's the type of "abc"
? 什么是
"abc"
类型? It's not std::string
, it's const char[4]
! 不是
std::string
,而是const char[4]
!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.