c++ - 作为可变参数模板的结构化参数

标签 c++ c++11 templates variadic

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

现在我想要一个(模板)方法来获取这些对中的 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::pair 但我得到的只是编译器错误:

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::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"});

关于c++ - 作为可变参数模板的结构化参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55140284/

相关文章:

c++ - 初始化通用模板化容器

c++ - 为什么必须在哪里放置 “template”和 “typename”关键字?

c++ - g++ : Compilation failed to deduce reference array in case of temporary object

c++ - (右值引用)VS(const 左值引用)作为 C++11 中的函数参数

c++ - 将 std::string 存储到 int[] 中用于 C++ 中的大整数

c++ - 有没有让我们将 "pass a namespace"放入模板的技巧?

c++ - 在 C++ 中转换函数指针的奇怪行为

c++ - 如何在 Bazel 项目中设置 Catch2

c++ - 按位 AND/OR 运算符追加?

c++ - 如何将现有的 C++ 代码移植到 C++11