Eva*_*ran 16 c++ parsing constexpr c++17
对不起,这将是一个很长的帖子,但我觉得你需要所有的代码来看看发生了什么.
所以,我一直在尝试将编译时字符串转换为数据结构解析器.想象一下像正则表达式这样的东西,其中字符串在编译时被"编译"成数据结构但在运行时执行(只要输入字符串当然是常量).但是我遇到了一个我不太明白错误的问题:
基本上,我的设计是一个2遍解析器:
这是事情的样子:
// a class to wrap string constants
class constexpr_string {
public:
template <size_t N>
constexpr constexpr_string(const char (&s)[N]) : string_(s), size_(N - 1) {}
public:
constexpr size_t size() const { return size_; }
constexpr size_t capacity() const { return size(); }
constexpr size_t empty() const { return size() != 0; }
public:
constexpr char operator[](size_t n) const { return string_[n]; }
private:
const char *string_;
size_t size_;
};
// would have loved to use std::array, but ran into an issue so..
// wrapped in a struct so we can return it
template <class T, size_t N>
struct constexpr_array {
T array[N] = {};
};
struct opcode { /* not relevant */ };
template <size_t N>
constexpr constexpr_array<opcode, N> compile_string(constexpr_string fmt) {
constexpr_array<opcode, N> compiled;
/* fill in compiled_format */
return compiled;
}
constexpr size_t calculate_size(constexpr_string fmt) {
size_t size = 0;
/* calculate size */
return size;
}
#if 0
// NOTE: Why doesn't **This** work?
constexpr int test(constexpr_string input) {
constexpr size_t compiled_size = calculate_size(input);
constexpr auto compiled_format = compile_string<compiled_size>(input);
return 0;
}
#endif
int main() {
// NOTE: when this works...
constexpr char input[] = "...";
constexpr size_t compiled_size = calculate_size(input);
constexpr auto compiled = compile_string<compiled_size>(input);
execute(compiled); // run it!
}
Run Code Online (Sandbox Code Playgroud)
到现在为止还挺好!
当我尝试将这两行包装成函数时出现问题: - /.我不明白为什么相同的确切代码适用main
,但如果我只是尝试将同一个constexpr
对象传递
给另一个函数,我开始得到关于不存在的事情的错误constexpr
.
这是错误消息:
main.cpp: In function ‘constexpr int test(constexpr_string)’:
main.cpp:258:55: error: ‘input’ is not a constant expression
constexpr size_t compiled_size = calculate_size(input);
^
main.cpp:259:70: error: no matching function for call to ‘compile_string<compiled_size>(constexpr_string&)’
constexpr auto compiled_format = compile_string<compiled_size>(input);
^
main.cpp:60:45: note: candidate: template<long unsigned int N> constexpr constexpr_array<opcode, N> compile_string(constexpr_string)
constexpr constexpr_array<opcode, N> compile_string(constexpr_string fmt) {
^~~~~~~~~~~~~~
main.cpp:60:45: note: template argument deduction/substitution failed:
Run Code Online (Sandbox Code Playgroud)
T.C*_*.C. 19
让我们减少这个:
constexpr void f(int i) {
constexpr int j = i; // error
}
int main() {
constexpr int i = 0;
constexpr int j = i; // OK
}
Run Code Online (Sandbox Code Playgroud)
函数参数永远不会constexpr
,因此i
inside f
不是常量表达式,不能用于初始化j
.一旦通过函数参数传递了某些东西,constexpr-ness就会丢失.