Can I invoke at run-time the logic for choosing wh

2019-08-17 05:23发布

问题:

In my C++ program I've got these three user-defined literal operators:

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 holds a number of hours (as a float) and a validity flag.

So I can say: Duration duration = 17_m;

And I can say: int m = 17; Duration duration = operator""_m(m);

But I can't say:

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

What I'm aiming for is something like that operator""_() that I just invented up there, with the compiler picking at run-time the appropriate operator to call. I know I could write something like this myself (in fact I've already done it in this case), but I don't think anything like it is already in the language. I'm asking here to confirm that: Is it in the language?

回答1:

Do you wish to implement your own parser? Here is a sketch that can be extended to the constexpr world:

#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 {};
}

If you do not care about constexpr then you should use one of the higher-level approaches suggested in @RemyLebeau's comment to this answer.