结构化参数为变异模板
structured arguments as variadic template
我有一个需要两个参数的方法:一个别名(字符串)和一个对象(任何类型的对象)。
现在,我想拥有一个(模板)方法,以这些对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"});
相关文章:
- 如何反转整数参数包
- 使用C++库在Android项目中修改gradle中的cmake参数,用于插入指令的测试
- 如何使用默认参数等选择模板专业化
- 模板参数替换失败,并且未完成隐式转换
- 具有默认模板参数的多态类的模板推导失败
- lambda参数转换为constexpr技巧,然后获取带链接的数组
- 具有变异模板模板参数的方法的部分专业化
- 我如何实现变异模式以将可变数量的参数转发到C 11中的函数
- 组合类模板默认参数和变异参数
- 继承具有变异参数的构造函数
- C 参数包作为变异模板
- 在没有参数的变异模板中迭代
- 结构化参数为变异模板
- C 是否允许在变异模板参数之后进行普通参数
- 计数宏函数中变异参数的数量
- 如何使模板通过变异参数推断返回类型的函数
- 为什么C 不允许在非模板函数中进行变异参数
- C :处理Visual Studio中的每个变异参数
- 为什么这个嵌套的变异模板是无效的参数
- 如何绑定变异模板参数与功能