繁体   English   中英

编译时检查sizeof…(args)是否与constexpr函数的结果匹配

[英]Compile time check if sizeof…(args) matches result from constexpr function

我有constexpr函数,该函数计算占位符的数量https://godbolt.org/g/JcxSiu

例如:“ Hello %1 ”返回1 ,而“ Hello %1, time is %2 ”返回2

然后,我想制作一个函数,如果参数数量不等于占位符数量,则该函数不会编译。

template <typename... Args>
 inline std::string make(const char* text, Args&&... args) {
   constexpr static unsigned count = sizeof...(args);

   // TODO how to compile time check if count == count_placeholders(text)    
  // constexpr static auto np = count_placeholders(text);

  //static_assert(count == np;, "Wrong number of arguments in make");

  return std::to_string(count);
};

这样make("Hello %1", "World"); 编译并

make("Hello %1 %2", "World"); make("Hello %1", "World", "John"); 才不是。

我想可以做到的,我只是不知道怎么做。 也许与一些模板magick :)

编辑

我几乎得到了我想要的。 https://godbolt.org/g/Y3q2f8

现在以调试模式中止。 是否有可能使编译时出错?

我的第一个想法是使用SFINAE启用/禁用make() 就像是

template <typename... Args>
auto make(const char* text, Args&&... args)
   -> std::enable_if_t<sizeof...(args) == count_placeholders(text),
                       std::string>
 {
    // ... 
 }

不幸的是,由于text不能在constexpr使用,因此无法编译。

但是,如果您接受text是模板参数(在编译时即为已知),则可以执行以下操作:

template <char const * const text, typename ... Args>
auto makeS (Args && ... args)
   -> std::enable_if_t<sizeof...(args) == count_plc(text), std::string>
 { return std::to_string(sizeof...(args)); }

以下是完整的工作示例

#include <string>
#include <type_traits>

constexpr std::size_t count_plc (char const * s,
                                 std::size_t index = 0U,
                                 std::size_t count = 0U)
 {
   if ( s[index] == '\0' )
      return count;
   else if (    (s[index] == '%')  && (s[index+1U] != '\0')
             && (s[index+1U] > '0') && (s[index+1U] <= '9') )
      return count_plc(s, index + 1U, count+1U);
   else
      return count_plc(s, index + 1U, count); 
 }

template <char const * const text, typename ... Args>
auto makeS (Args && ... args)
   -> std::enable_if_t<sizeof...(args) == count_plc(text), std::string>
 { return std::to_string(sizeof...(args)); }

constexpr char const h1[] { "Hello %1" };
constexpr char const h2[] { "Hello %1 %2" };

int main ()
 {
   makeS<h1>("World"); // compile
   //makeS<h2>("World"); // compilation error
   //makeS<h1>("World", "John"); // compilation error
 }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM