结构化参数作为可变参数模板

问题描述 投票:1回答:1

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

现在我想要一个(模板)方法来获取这些对中的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});

有人有想法吗?

c++ c++11 templates variadic
1个回答
2
投票

你可以使用boost :: assign或类似的东西:

 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"});
© www.soinside.com 2019 - 2024. All rights reserved.