是否可以从字符串创建可变元组?

Mai*_*ein 3 c++ c++11 c++14

constexpr std::tuple<int,char,int,char> t1 = parse("1a2b");
constexpr std::tuple<int,int,int,char> t2 = parse("123a");
constexpr std::tuple<char,int> t3 = parse("a2");
Run Code Online (Sandbox Code Playgroud)

这样的事情会成为可能吗?

我对TMP并不完全流利,但我从以下开始

template<std::size_t N,typename ...Args> constexpr
std::tuple<Args...> parse(const char* s[N]){
  constexpr char c = s[0];
  constexpr char* new_s[N-1] = "";
  for (int i = 1; i < N; i++) {
    new_s[i] = s[i];
  }
  //my own constexpr isdigit
  if(!isdigit(c)){
    return parse(new_s,c);
  }
  else if(isdigit(c)){
    return parse(new_s,static_cast<int>(c));
  }
  throw std::invalid_argument("");
}
...
Run Code Online (Sandbox Code Playgroud)

我想以递归方式执行此操作并累积元组,但我很快意识到每次传入新元组时类型都会改变.

T.C*_*.C. 5

由于parse必须返回不同类型"1a2b""123a",很明显,包括字符串文字字符必须是模板参数的一部分.这样做很容易

constexpr bool my_isdigit(char c){
    return c >= '0' && c <= '9';
}
template<char c, bool = my_isdigit(c)>
struct mapper {
    using type = char;
    static constexpr char value = c;
};

template<char c>
struct mapper<c, true> {
    using type = int;
    static constexpr int value = c - '0';
};

template<char... chars> 
constexpr auto parse(){
    return std::tuple<typename mapper<chars>::type...>(mapper<chars>::value...);
}

constexpr auto p = parse<'1', 'a', '2', 'b'>();
Run Code Online (Sandbox Code Playgroud)

如果你真的想使用字符串文字,可以使用一些技巧将字符串文字分解为参数包.