是否可以在运行时调用用于选择要调用的用户定义文本的逻辑?

Can I invoke at run-time the logic for choosing which user-defined literal to call?

本文关键字:调用 用户 定义 文本 选择 运行时 是否 用于      更新时间:2023-10-16

在我的C++程序中,我有这三个用户定义的文字运算符:

constexpr Duration operator""_h(unsigned long long int count) { return {count / 1.f, true}; }
constexpr Duration operator""_m(unsigned long long int count) { return {count / 60.f, true}; }
constexpr Duration operator""_s(unsigned long long int count) { return {count / 3600.f, true}; }

持续时间包含小时数(作为浮点数(和有效性标志。

所以我可以说:Duration duration = 17_m;

我可以说:int m = 17; Duration duration = operator""_m(m);

但我不能说:

const char* m = "17_m"; Duration duration1 = operator""_(m);
const char* h = "17_h"; Duration duration2 = operator""_(h);

我的目标是类似于我刚刚发明的operator""_(),编译器在运行时选择要调用的适当运算符。 我知道我可以自己写这样的东西(事实上我已经在这种情况下写过了(,但我认为语言中没有这样的东西。 我在这里要求确认:它是在语言中吗?

你想实现你自己的解析器吗?这是一个可以扩展到constexpr世界的草图:

#include <cassert>
#include <cstdlib>
#include <iostream>
constexpr Duration parse_duration(const char* input) {// input: Ad*_[hms]z
int numeric_value = 0;
// TODO: handle negative values, decimal, whitespace...
std::size_t pos = 0;
while(input[pos] != '_') {
unsigned digit = unsigned(input[pos++]) - unsigned('0');
assert(digit <= 9);
numeric_value *= 10;
numeric_value += digit;
}
char unit = input[pos+1];
assert(input[pos+2] == '' && "must end with '' after one-letter unit");
switch(unit) {
case 'h': return operator""_h(numeric_value);
case 'm': return operator""_m(numeric_value);
case 's': return operator""_s(numeric_value);
default: std::cerr << unit << std::endl;
}
assert(false && "unknown unit");
return {};
}

如果你不关心constexpr那么你应该使用@RemyLebeau对此答案的评论中建议的更高层次的方法之一。