是否可以在运行时调用用于选择要调用的用户定义文本的逻辑?
Can I invoke at run-time the logic for choosing which user-defined literal to call?
在我的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对此答案的评论中建议的更高层次的方法之一。
相关文章:
- 使用用户定义的参数调用future/async并调用类方法
- 为用户定义的类正确调用复制构造函数/赋值运算符
- 用户控制从 c++ 到 java 脚本的 Webassembly 访问调用
- 是否可以在运行时调用用于选择要调用的用户定义文本的逻辑?
- 在左值上调用用户定义的文本
- 错误:调用'strcmp'没有匹配函数(尝试设置显示用户信息功能)
- 程序在调用函数时跳过用户输入
- 从 Windows KMD 调用用户空间 API 函数
- C 17:始终调用用户定义的构造函数,并且运算符 超载不适用于儿童课程
- 是否可以保证模板模板参数调用用户提供的演绎指南
- 如何在C 中调用用户定义的功能
- 是否可以通过列表初始化调用用户定义的转换函数
- API 需要调用用户实现的函数
- 内核模块定期调用用户空间程序
- C++编译器不允许我使用数组作为参数来调用用户定义的函数
- 如何调用用户定义对象的类型转换例程
- 当有额外的括号时,在临时对象上调用用户定义的操作符+出错
- 调用'new'如何调用用户定义的放置分配函数?
- 对std::array中的元素调用用户定义的构造函数
- sql server 2008-如何使用ADO从c++调用用户定义的函数