c++ - 我可以在运行时调用选择调用哪个用户定义文字的逻辑吗?

标签 c++ user-defined-literals

在我的 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 包含小时数(作为 float )和有效性标志。

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

我可以说:int m = 17;持续时间 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: \A\d*_[hms]\z\0
  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] == '\0' && "must end with '\0' 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 对此答案的评论中建议的一种更高级别的方法。

关于c++ - 我可以在运行时调用选择调用哪个用户定义文字的逻辑吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51885765/

相关文章:

c++ - 基于对话框的 Win32 API 程序在使用 Richedit 控件时不会显示窗口

c++ - 在我构建霍夫曼树后,当我读取 5megs 的数据时,根的权重为 700k

c++ - FreeFileSync C++ 错误 : 'byte' is not a member of 'std'

C++:使用后缀设置时间

c++ - 什么是 C++20 的字符串文字运算符模板?

c++ - scoped_lock 如何避免发出 "unused variable"警告?

c++ - AIX unix 服务器上的 g++ 编译错误

c++ - 在 C++ 中方便地声明编译时字符串

c++ - 文字运算符的模板参数列表

c++ - 基于字符串的用户定义文字可以是强类型的吗?