Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Concatenating strings (and numbers) in variadic template function

I am attempting to write a function that takes a variety of strings or numbers (that work with std::to_string and concatenate them. I've got it working with just strings, but I am having trouble with specializing depending on input as string or number.

My code is called like this:

stringer("hello", "world", 2, 15, 0.2014, "goodbye", "world")

And here is what I've got:

inline std::string stringer(const std::string &string)
{
    return string;
}

template <typename T, typename... Args>
inline std::string stringer(const std::string &string, T &&val, Args &&...args)
{  
    return stringer(string+std::to_string(val), std::forward<Args>(args)...);
}

template <typename... Args>
inline std::string stringer(const std::string &string, Args &&...args)
{
    return stringer(string, std::forward<Args>(args)...);
}

Currently it is breaking on any more than one string added unless the following are all numbers (due to the to_string). How can I specialize based on string or number to make the above work? Thanks.

like image 963
jett Avatar asked Feb 16 '14 02:02

jett


6 Answers

inline std::string const& to_string(std::string const& s) { return s; }

template<typename... Args>
std::string stringer(Args const&... args)
{
    std::string result;
    using ::to_string;
    using std::to_string;
    int unpack[]{0, (result += to_string(args), 0)...};
    static_cast<void>(unpack);
    return result;
}
like image 160
Simple Avatar answered Oct 05 '22 00:10

Simple


Why do not use simple std::stringstream ?

#include <iostream>
#include <string>
#include <sstream>

template< typename ... Args >
std::string stringer(Args const& ... args )
{
    std::ostringstream stream;
    using List= int[];
    (void)List{0, ( (void)(stream << args), 0 ) ... };

    return stream.str();
}

int main()
{
    auto s = stringer("hello", ' ', 23, ' ', 3.14, " Bye! " );

    std::cout << s << '\n';
}
like image 24
Khurshid Avatar answered Oct 05 '22 01:10

Khurshid


Three more ways to do this:

  1. Similar to Khurshid's but without unnecessary array of ints
  2. Similar to Simple's and Khurshid's but builds on older compilers
  3. Recurent way

And the code:

#include <iostream>
#include <sstream>

// First version:
template<typename T>
std::string toString(T value)
{
    std::ostringstream oss;
    oss << value;
    return oss.str();
}

std::string merge(std::initializer_list<std::string> strList)
{
    std::string ret = "";
    for (std::string s : strList) {
        ret += s;
    }
    return ret;
}

template< typename ... Args >
std::string stringer1(const Args& ... args)
{
    return merge({toString(args)...});
}


// Second version:
template< typename ... Args >
std::string stringer2(const Args& ... args)
{
    std::ostringstream oss;
    int a[] = {0, ((void)(oss << args), 0) ... };

    return oss.str();
}


// Third version:
template<typename T>
std::string stringer3(const T& value)
{
    std::ostringstream oss;
    oss << value;
    return oss.str();
}

template<typename T, typename ... Args >
std::string stringer3(const T& value, const Args& ... args)
{
    return stringer3(value) + stringer3(args...);
}

int main()
{
    int a, b;
    std::cout << stringer1("a", 1) << std::endl;
    std::cout << stringer2("b", 2) << std::endl;
    std::cout << stringer3("c", 3) << std::endl;

// Output:
//     a1
//     b2
//     c3
}
like image 37
Janek Olszak Avatar answered Oct 05 '22 00:10

Janek Olszak


With C++17 we now have fold expressions to simplify this:

#include <sstream>

// cat - Concatenate values of arbitrary types into a string.
template <typename... Ts>
std::string cat(Ts&&... args) {
  std::ostringstream oss;
  (oss << ... << std::forward<Ts>(args));
  return oss.str();
}
like image 40
Matt Avatar answered Oct 05 '22 01:10

Matt


Per request, here's a (longer) solution with SFINAE:

namespace detail {
    using std::to_string;

    std::string
    concat()
    {
        return "";
    }

    template<typename Head, typename... Tail>
    decltype( to_string(std::declval<Head>()) )
    concat(Head&& h, Tail&&... t);

    template<typename Head, typename... Tail>
    decltype(std::string() + std::declval<Head>())
    concat(Head&& h, Tail&&... t)
    {
        return std::forward<Head>(h) + concat(std::forward<Tail>(t)...);
    }

    template<typename Head, typename... Tail>
    decltype( to_string(std::declval<Head>()) )
    concat(Head&& h, Tail&&... t)
    {
        return to_string(std::forward<Head>(h)) + concat(std::forward<Tail>(t)...);
    }
}

template<typename... Args>
std::string concat(Args&&... args)
{
    return detail::concat(std::forward<Args>(args)...);
}

Can be seen in action here: http://coliru.stacked-crooked.com/a/77e27eaabc97b86b

Note that it assumes, for a given type, either string concatenation (with +) or to_string() is defined, but not both. So std::string, const char* and any 3rd party string class that interacts naturally with std::string should go through the + version. Of course, if the 3rd party string class does something silly like defining both concatenation and to_string() this will be ambiguous; you would need to define has_string_concat and has_to_string type predicates to have control on how to resolve the ambiguity.

I'm also putting everything in a namespace to be able to use argument-dependent lookup to select the right version of to_string; the full example shows a user-defined type with its own to_string().

like image 28
DanielKO Avatar answered Oct 05 '22 01:10

DanielKO


In C++ 11, doing it in variadic templates way works for me. It also enforces user to provide at least one argument. inline is helpful if you are defining functions in header file.

#include <sstream>

template< typename T >
inline std::string stringify(const T& t)
{
    std::stringstream string_stream;
    string_stream << t;
    return string_stream.str();
}

template< typename T, typename ... Args >
inline std::string stringify(const T& first, Args ... args)
{
    return stringify( first ) + stringify( args... );
}
like image 25
shaffooo Avatar answered Oct 05 '22 02:10

shaffooo