Reputation: 101
I've a method needing two parameters: An alias (string) and an object (of any type).
Now I would like to have a (template) method taking n of those pairs; The syntax should look like this:
append (
{ "first", int { 3 } },
{ "second", double { 2. } },
{ "third", std::string { "test" } }
);
What I currently do is following:
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");
}
Which makes it possible to write something like this
append (
"first", int { 3 },
"second", double { 2. },
"third", std::string { "test" }
);
But in my opinion it would make the code more readable, if I could use the curly Braces like in my example above.
What I've tried to do is use a templated std::pair but all I get are compiler errors:
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});
Does someone have an idea?
Upvotes: 2
Views: 89
Reputation: 37547
You can probably use boost::assign or something similar:
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};
}
usage:
Append(::std::cout)
("first", int{3})
("second", double{2.0})
("third", ::std::string{"test"});
Upvotes: 2