结构化参数为变异模板

structured arguments as variadic template

本文关键字:变异 参数 结构化      更新时间:2023-10-16

我有一个需要两个参数的方法:一个别名(字符串)和一个对象(任何类型的对象)。

现在,我想拥有一个(模板)方法,以这些对n;语法应该看起来像这样:

append (
  { "first", int { 3 } },
  { "second", double { 2. } },
  { "third", std::string { "test" } }
);

我目前要做的是以下内容:

void append() {}
template<typename Type>
void append(std::string str, Type obj)
{
  std::cout << "str: " << str << " type: " << obj << "n";
}
template<typename Type, typename... Args>
void append(std::string str, Type t, Args... args)
{
  append(str, t);
  append(args...);
}
int main()
{
 append("first", 1, "second", 2., "third, "test");
}

可以写下类似的东西

append (
  "first", int { 3 },
  "second", double { 2. },
  "third", std::string { "test" }
);

,但我认为,如果我可以在上面的示例中使用卷发括号,则可以使代码更可读。

我尝试使用的是使用模板的std ::配对,但我得到的只是编译器错误:

main.cpp:9:6: note: template<class Type> void 
append(std::initializer_list<std::pair<std::basic_string<char>, Type> >)
 void append(std::initializer_list<std::pair<std::string, Type>> pair)
      ^
main.cpp:9:6: note:   template argument deduction/substitution failed:
main.cpp:23:22: note:   couldn't deduce template parameter ‘Type’
  append({"first", 1});

有人有主意吗?

您可能可以使用boost ::或类似的东西:

 class t_Append final
 {
     private: ::std::ostream & m_where;
     public: explicit
     t_Append
     (
         ::std::ostream & where
     ) noexcept
     :   m_where{where}
     {
         return;
     }
     public: explicit
     t_Append
     (
          t_Append && other
     ) noexcept
     :    m_where{other.m_where}
     {
          return;
     }
     public: template
     <
         typename x_Object
     > auto
     operator ()
     (
          char const * const psz_str
     ,    x_Object const & object
     ) &&
     {
          m_where << "str: " << psz_str << " type: " << object << "n";
          return t_Append{::std::move(*this)};
     }
 };
 inline auto
 Append(::std::ostream & where)
 {
     return t_Append{where};
 }

用法:

 Append(::std::cout)
     ("first", int{3})
     ("second", double{2.0})
     ("third", ::std::string{"test"});