Can I template this to avoid rewriting the class? - c++

I've got a class that's rewritten for certain special cases, but I was wondering if it's possible to use C++ generic programming to decide what a function contains:
#include <iostream>
#include <typeinfo>
#include <string>
void printString(const std::string& str) { std::cout << str.c_str() << '\n'; }
template <typename T_callable>
struct FuncResultToString
{
FuncResultToString(T_callable func) : call(func) {}
T_callable call;
void turnFuncResultToString()
{
std::string str = "Type: ";
str += typeid(decltype(call())).name();
str += " / Value: ";
// IF RETURN TYPE IS CHAR* OR STRING
str += call();
// ELSE WILL HAVE TO TURN TO STRING FIRST
str += std::to_string(call());
printString(str);
}
};
double afunction() { return double(5.0); }
int main()
{
FuncResultToString<decltype(&afunction)> foo1(afunction);
foo1.turnFuncResultToString();
auto lambda = []() { return int(7); };
FuncResultToString<decltype(lambda)> foo2(lambda);
foo2.turnFuncResultToString();
}
This prints out:
Type: double / Value: 5.000000
Type: int / Value: 7
Which is fine for many types, but in the case the callable returns a char pointer or std::string I don't want to call std::to_string(), I just want to use the value as is. Is there a way of doing this?

You can have overload:
const char* my_to_string(const char* s) { return s; }
const std::string& my_to_string(const std::string& s) { return s; }
template <typename T> std::string my_to_string(const T& s) { return std::to_string(s); }
And then:
void turnFuncResultToString()
{
std::string str = "Type: ";
str += typeid(decltype(call())).name();
str += " / Value: ";
str += my_to_string(call());
printString(str);
}

The naive solution would be
void turnFuncResultToString()
{
std::cout << "Type: ";
std::cout << typeid(decltype(call())).name();
std::cout << " / Value: ";
std::cout << call();
}
If you need the string itself you can use a std::stringstream ss; instead of std::cout and then printString(ss.str());.

Related

print the name of a function's input that was given as reference [duplicate]

I am looking for a functionality that allows logging a function input arguments. For example:
void func(std::string& input_name, const int n){
// print current function's inputs' type, name, and value
}
which after the function is called, the following will be printed or readable as string,
input1:
type: std::string,
name: input_name,
value: "something",
input2:
type: int,
name: n,
value: 12,
does anyone have a suggestion for such goal
------------edit
it is also ok for me if printing the type or name is not possible.
I am flexible with a solution close to this, like if we can get a list of input arguments, or etc.
Printing a variable's type and value is fairly simple. But variable names don't exist at runtime, so the only way to obtain a variable's name as a string, without hard-coding it, is to use a macro at compile-time. Macros have a feature to stringify tokens.
Try something like this (sorry, this is from memory, I can't get to a compiler at the moment, I'll update this later today):
#include <iomanip>
#include <typeinfo>
#include <type_traits>
template <typename T>
std::string getTypeName()
{
// TODO: to get a more human-readable output, use
// if-constexpr, or template specialization, or one
// of the solutions from https://stackoverflow.com/q/281818/65863...
return typeid(T).name();
}
template<typename T>
std::string stringify(const T& param)
{
std::ostringstream oss;
if constexpr (std::is_same_v<T, std::string> || std::is_same_v<T, char*> || std::is_same_v<T, const char*>)
oss << std::quoted(param);
else
oss << param;
return oss.str();
}
template <typename T>
void doLog(int num, std::string_view name, const T& value)
{
std::cout << "input" << num << ":" << std::endl
<< "\ttype: " << getTypeName<T>() << "," << std::endl
<< "\tname: " << #param << "," << std::endl
<< "\tvalue: " << stringify(param) << "," << std::endl;
}
#define LOG(num, param) doLog(num, #param, param)
void func(std::string& input_name, const int n){
LOG(1, input_name)
LOG(2, n)
}
This is a start using templates instead of macros :
(Indeed with the added notion that typeid.name can output mangled names)
#include <iostream>
#include <string>
#include <sstream>
namespace details
{
//-------------------------------------------------------------------------
// formatters for parameters to functions
//
template<typename type_t>
std::string format(const type_t& value)
{
std::ostringstream os;
os << typeid(type_t).name() << ":";
os << value;
return os.str();
}
// output boolean as text
std::string format(const bool& value)
{
return value ? std::string("bool:true") : std::string("bool:false");
}
// add quotes to string
std::string format(const char* value)
{
std::ostringstream os;
os << "const char*:\"";
os << value;
os << "\"";
return os.str();
}
// recursively log all parameters
template<typename arg_t, typename... args_t>
inline void log_parameters(bool comma, const arg_t& arg, args_t... args)
{
if (comma) std::cout << ", ";
std::cout << format(arg);
if constexpr (sizeof...(args_t) > 0)
{
// true is print separating comma at next call
log_parameters(true, std::forward<args_t>(args)...);
}
}
//-------------------------------------------------------------------------
template<typename... args_t>
inline void log(const char* function, args_t... args)
{
std::cout << "function call to : " << function << "(";
// if there are any arguments to log do so
if constexpr (sizeof...(args_t) > 0)
{
// false == do not print a comma on first call
log_parameters(false, std::forward<args_t>(args)...);
}
std::cout << ");\n";
}
}
void my_function(const bool x, const int y, const char* str)
{
details::log(__FUNCTION__, x, y, str);
}
int main()
{
my_function(1, 42, "Hello world!");
}

Overload the subscript operator to call a function based on the type assigned

I have an object that has functions like addString and addInteger. These functions add data to a JSON string. At the end, the JSON string can be obtained and sent out. How can this be made easier by overloading subscript operators to do the following?
jsonBuilder builder();
builder[ "string_value" ] = "Hello";
builder[ "int_value" ] = 5;
builder[ "another_string" ] = "Thank you";
You need to have a proxy class that is returned by the operator[] function and which handles the assignment. The proxy class then overloads the assignment operator to handle strings and integers differently.
Something like this:
#include <iostream>
#include <string>
struct TheMainClass
{
struct AssignmentProxy
{
std::string name;
TheMainClass* main;
AssignmentProxy(std::string const& n, TheMainClass* m)
: name(n), main(m)
{}
TheMainClass& operator=(std::string const& s)
{
main->addString(name, s);
return *main;
}
TheMainClass& operator=(int i)
{
main->addInteger(name, i);
return *main;
}
};
AssignmentProxy operator[](std::string const& name)
{
return AssignmentProxy(name, this);
}
void addString(std::string const& name, std::string const& str)
{
std::cout << "Adding string " << name << " with value \"" << str << "\"\n";
}
void addInteger(std::string const& name, int i)
{
std::cout << "Adding integer " << name << " with value " << i << "\n";
}
};
int main(int argc __attribute__((unused)), char *argv[] __attribute__((unused)))
{
TheMainClass builder;
builder[ "string_value" ] = "Hello";
builder[ "int_value" ] = 5;
builder[ "another_string" ] = "Thank you";
}
See here for a working example.
I think you need this finally. I have implemented for getting the string input, do the same for integer.
#include <iostream>
#include <string>
#include <map>
class jsonBuilder
{
public:
std::map<std::string,std::string> json_container;
std::string& operator[](char *inp)
{
std::string value;
json_container[std::string(inp)];
std::map<std::string,std::string>::iterator iter=json_container.find(std::string(inp));
return iter->second;
}
};
int main()
{
jsonBuilder jb;
jb["a"]="b";
std::map<std::string,std::string>::iterator iter=jb.json_container.find(std::string("a"));
std::cout<<"output: "<<iter->second;
}

passing primitive data type to a function in c++

I want to implement a function like this
double d = string_to("1223.23",double);
int i = string_to("1223",int);
bool d = string_to("1",bool);
How can I pass the bool, int, double data type to implement this in c++?
Types line int, double and bool can only be passed as template parameters.
You can use templates like this:
#include <string>
#include <sstream>
#include <iostream>
template<typename DataType>
DataType string_to(const std::string& s)
{
DataType d;
std::istringstream(s) >> d; // convert string to DataType
return d;
}
int main()
{
double d = string_to<double>("1223.23");
int i = string_to<int>("1223");
bool b = string_to<bool>("1");
std::cout << "d: " << d << '\n';
std::cout << "i: " << i << '\n';
std::cout << "b: " << b << '\n';
}
As an alternative you can pass your numeric types by reference and rely on function overloading to select the correct function:
void string_to(const std::string& s, double& d)
{
d = std::stod(s);
}
void string_to(const std::string& s, int& i)
{
i = std::stoi(s);
}
void string_to(const std::string& s, bool& b)
{
std::istringstream(s) >> std::boolalpha >> b;
}
int main()
{
double d;
int i;
bool b;
string_to("1223.23", d);
string_to("1223", i);
string_to("true", b);
std::cout << "d: " << d << '\n';
std::cout << "i: " << i << '\n';
std::cout << "b: " << b << '\n';
}
Also you could templatize the second method (an exercise for the reader).
If you really want to do this, you can pass the type by using the typeid operator.
E.g. double d = string_to("1223.23", typeid(double));
Using the library functions atoi, stod would make more sense.
If you're aiming to write more uniform code then you could write a Converter object and use method overloading to get automatic selection by type.
class Converter
{
public:
void fromString(double& value, const char* string);
void fromString(int& value, const char* string);
void fromString(long& value, const char* string);
};
Here's another way that uses tag dispatching. You can compile and run this example.
#include <iostream>
#include <string>
#include <cmath>
namespace detail {
// declare the concept of conversion from a string to something
template<class To>
To string_to(const std::string&);
// make some models of the concept
template<>
int string_to<int>(const std::string& s) {
return atoi(s.c_str());
}
template<>
double string_to<double>(const std::string& s) {
return atof(s.c_str());
}
template<>
std::string string_to<std::string>(const std::string& s) {
return s;
}
// ... add more models here
}
// define the general case of conversion from string with a model tag
// note the unused parameter allows provision of a model that is never used
// thus the model will in all likelihood be optimised away
template<class To>
To string_to(const std::string& from, const To& /* model_tag is unused */)
{
// dispatch to correct conversion function using the To type
// as a dispatch tag type
return detail::string_to<To>(from);
}
using namespace std;
int main()
{
// examples
int a = string_to("100", a);
double b = string_to("99.9", b);
const string s = string_to("Hello", s);
cout << s << " " << a << " " << b << endl;
return 0;
}
output:
Hello 100 99.9

Generic way to convert a string into a numerical type?

I have this class:
template<typename T> class Parser
{
public:
Parser() : count(0) {}
virtual void parse(const string&);
void get_token(void);
private:
T result;
char token;
string expression;
int count;
};
now had the class not been generic, had the result been say, a double, I would have used this method to detect numbers.
while((strchr("1234567890.",token))
{
/* add token to a "temp" string */
/* etc. etc. */
}
result = atof(temp.c_str());
But since result is generic, I can't use any method like atof and atoi etc.
What do I do?
Boost has this functionality built-in:
#include <boost/lexical_cast.hpp>
void Parser<T>::get_token() {
std::string token = ...;
result = boost::lexical_cast<T>(token);
}
Add exception handling as required.
Or, perhaps you don't want to use Boost for some reason:
void Parser<T>::get_token() {
std::string token = ...;
std::stringstream ss;
ss << token;
ss >> result;
}
Check the error state of ss as required.
More expansive answers may be found on this related question, though it discusses only int specifically.
Another generic template based Numeric To String converter. It takes ints and doubles.
#include <sstream>
#include <iostream>
#include <string>
using namespace std;
template <class T>
inline std::string Numeric_To_String (const T& t)
{
std::stringstream ss;
ss << t;
return ss.str();
}
int main(int argc, char *argv[])
{
int i = 9;
double d = 1.2345;
string s;
cout <<"Generic Numeric_To_String( anyDatatype ) \n\n";
s = Numeric_To_String( i );
cout <<"int i to string : "<< s <<" "<< endl;
s = Numeric_To_String( d );
cout <<"double d to string : "<< s <<" "<< endl;
cout <<" \n";
return 0;
}
If you only have a hand full of types you want to parse, you can use template specialization:
template<>
void Parser<int>::parse(const string&)
{
result = atoi(string.c_str());
}
template<>
void Parser<float>::parse(const string&)
{
result = atof(string.c_str());
}
...
But this only works if you implement every convertion you need, of course.
With C++17 you can use the templated std::from_chars.
https://en.cppreference.com/w/cpp/utility/from_chars
#include <charconv>
#include <iostream>
template <typename Number>
auto stringTo(std::string_view str)
{
Number number;
std::from_chars(str.data(), str.data() + str.size(), number);
return number;
}
int main()
{
const auto str = std::string("42");
std::cout << stringTo<long>(str) << '\n';
std::cout << stringTo<double>(str) << '\n';
}
Check the return value of std::from_chars to detect errors.
const auto result = std::from_chars(...);
if (result.ec == std::errc::invalid_argument || result.ec == std::errc::result_out_of_range)
{
std::cout << "string to number error" << '\n';
}
More info and examples: https://www.bfilipek.com/2018/12/fromchars.html
GCC and clang don't yet support the floating point version of std::from_chars (August 2019).

How do I concatenate multiple C++ strings on one line?

C# has a syntax feature where you can concatenate many data types together on 1 line.
string s = new String();
s += "Hello world, " + myInt + niceToSeeYouString;
s += someChar1 + interestingDecimal + someChar2;
What would be the equivalent in C++? As far as I can see, you'd have to do it all on separate lines as it doesn't support multiple strings/variables with the + operator. This is OK, but doesn't look as neat.
string s;
s += "Hello world, " + "nice to see you, " + "or not.";
The above code produces an error.
#include <sstream>
#include <string>
std::stringstream ss;
ss << "Hello, world, " << myInt << niceToSeeYouString;
std::string s = ss.str();
Take a look at this Guru Of The Week article from Herb Sutter: The String Formatters of Manor Farm
In 5 years nobody has mentioned .append?
#include <string>
std::string s;
s.append("Hello world, ");
s.append("nice to see you, ");
s.append("or not.");
s += "Hello world, " + "nice to see you, " + "or not.";
Those character array literals are not C++ std::strings - you need to convert them:
s += string("Hello world, ") + string("nice to see you, ") + string("or not.");
To convert ints (or any other streamable type) you can use a boost lexical_cast or provide your own function:
template <typename T>
string Str( const T & t ) {
ostringstream os;
os << t;
return os.str();
}
You can now say things like:
string s = string("The meaning is ") + Str( 42 );
Your code can be written as1,
s = "Hello world," "nice to see you," "or not."
...but I doubt that's what you're looking for. In your case, you are probably looking for streams:
std::stringstream ss;
ss << "Hello world, " << 42 << "nice to see you.";
std::string s = ss.str();
1 "can be written as" : This only works for string literals. The concatenation is done by the compiler.
Using C++14 user defined literals and std::to_string the code becomes easier.
using namespace std::literals::string_literals;
std::string str;
str += "Hello World, "s + "nice to see you, "s + "or not"s;
str += "Hello World, "s + std::to_string(my_int) + other_string;
Note that concatenating string literals can be done at compile time. Just remove the +.
str += "Hello World, " "nice to see you, " "or not";
In C++20 you'll be able to do:
auto s = std::format("{}{}{}", "Hello world, ", myInt, niceToSeeYouString);
Until then you could do the same with the {fmt} library:
auto s = fmt::format("{}{}{}", "Hello world, ", myInt, niceToSeeYouString);
Disclaimer: I'm the author of {fmt}.
To offer a solution that is more one-line-ish: A function concat can be implemented to reduce the "classic" stringstream based solution to a single statement.
It is based on variadic templates and perfect forwarding.
Usage:
std::string s = concat(someObject, " Hello, ", 42, " I concatenate", anyStreamableType);
Implementation:
void addToStream(std::ostringstream&)
{
}
template<typename T, typename... Args>
void addToStream(std::ostringstream& a_stream, T&& a_value, Args&&... a_args)
{
a_stream << std::forward<T>(a_value);
addToStream(a_stream, std::forward<Args>(a_args)...);
}
template<typename... Args>
std::string concat(Args&&... a_args)
{
std::ostringstream s;
addToStream(s, std::forward<Args>(a_args)...);
return s.str();
}
boost::format
or std::stringstream
std::stringstream msg;
msg << "Hello world, " << myInt << niceToSeeYouString;
msg.str(); // returns std::string object
auto s = string("one").append("two").append("three")
The actual problem was that concatenating string literals with + fails in C++:
string s;
s += "Hello world, " + "nice to see you, " + "or not.";
The above code produces an error.
In C++ (also in C), you concatenate string literals by just placing them right next to each other:
string s0 = "Hello world, " "nice to see you, " "or not.";
string s1 = "Hello world, " /*same*/ "nice to see you, " /*result*/ "or not.";
string s2 =
"Hello world, " /*line breaks in source code as well as*/
"nice to see you, " /*comments don't matter*/
"or not.";
This makes sense, if you generate code in macros:
#define TRACE(arg) cout << #arg ":" << (arg) << endl;
...a simple macro that can be used like this
int a = 5;
TRACE(a)
a += 7;
TRACE(a)
TRACE(a+7)
TRACE(17*11)
(live demo ...)
or, if you insist in using the + for string literals (as already suggested by underscore_d):
string s = string("Hello world, ")+"nice to see you, "+"or not.";
Another solution combines a string and a const char* for each concatenation step
string s;
s += "Hello world, "
s += "nice to see you, "
s += "or not.";
You would have to define operator+() for every data type you would want to concenate to the string, yet since operator<< is defined for most types, you should use std::stringstream.
Damn, beat by 50 seconds...
If you write out the +=, it looks almost the same as C#
string s("Some initial data. "); int i = 5;
s = s + "Hello world, " + "nice to see you, " + to_string(i) + "\n";
As others said, the main problem with the OP code is that the operator + does not concatenate const char *; it works with std::string, though.
Here's another solution that uses C++11 lambdas and for_each and allows to provide a separator to separate the strings:
#include <vector>
#include <algorithm>
#include <iterator>
#include <sstream>
string join(const string& separator,
const vector<string>& strings)
{
if (strings.empty())
return "";
if (strings.size() == 1)
return strings[0];
stringstream ss;
ss << strings[0];
auto aggregate = [&ss, &separator](const string& s) { ss << separator << s; };
for_each(begin(strings) + 1, end(strings), aggregate);
return ss.str();
}
Usage:
std::vector<std::string> strings { "a", "b", "c" };
std::string joinedStrings = join(", ", strings);
It seems to scale well (linearly), at least after a quick test on my computer; here's a quick test I've written:
#include <vector>
#include <algorithm>
#include <iostream>
#include <iterator>
#include <sstream>
#include <chrono>
using namespace std;
string join(const string& separator,
const vector<string>& strings)
{
if (strings.empty())
return "";
if (strings.size() == 1)
return strings[0];
stringstream ss;
ss << strings[0];
auto aggregate = [&ss, &separator](const string& s) { ss << separator << s; };
for_each(begin(strings) + 1, end(strings), aggregate);
return ss.str();
}
int main()
{
const int reps = 1000;
const string sep = ", ";
auto generator = [](){return "abcde";};
vector<string> strings10(10);
generate(begin(strings10), end(strings10), generator);
vector<string> strings100(100);
generate(begin(strings100), end(strings100), generator);
vector<string> strings1000(1000);
generate(begin(strings1000), end(strings1000), generator);
vector<string> strings10000(10000);
generate(begin(strings10000), end(strings10000), generator);
auto t1 = chrono::system_clock::now();
for(int i = 0; i<reps; ++i)
{
join(sep, strings10);
}
auto t2 = chrono::system_clock::now();
for(int i = 0; i<reps; ++i)
{
join(sep, strings100);
}
auto t3 = chrono::system_clock::now();
for(int i = 0; i<reps; ++i)
{
join(sep, strings1000);
}
auto t4 = chrono::system_clock::now();
for(int i = 0; i<reps; ++i)
{
join(sep, strings10000);
}
auto t5 = chrono::system_clock::now();
auto d1 = chrono::duration_cast<chrono::milliseconds>(t2 - t1);
auto d2 = chrono::duration_cast<chrono::milliseconds>(t3 - t2);
auto d3 = chrono::duration_cast<chrono::milliseconds>(t4 - t3);
auto d4 = chrono::duration_cast<chrono::milliseconds>(t5 - t4);
cout << "join(10) : " << d1.count() << endl;
cout << "join(100) : " << d2.count() << endl;
cout << "join(1000) : " << d3.count() << endl;
cout << "join(10000): " << d4.count() << endl;
}
Results (milliseconds):
join(10) : 2
join(100) : 10
join(1000) : 91
join(10000): 898
Here's the one-liner solution:
#include <iostream>
#include <string>
int main() {
std::string s = std::string("Hi") + " there" + " friends";
std::cout << s << std::endl;
std::string r = std::string("Magic number: ") + std::to_string(13) + "!";
std::cout << r << std::endl;
return 0;
}
Although it's a tiny bit ugly, I think it's about as clean as you cat get in C++.
We are casting the first argument to a std::string and then using the (left to right) evaluation order of operator+ to ensure that its left operand is always a std::string. In this manner, we concatenate the std::string on the left with the const char * operand on the right and return another std::string, cascading the effect.
Note: there are a few options for the right operand, including const char *, std::string, and char.
It's up to you to decide whether the magic number is 13 or 6227020800.
Maybe you like my "Streamer" solution to really do it in one line:
#include <iostream>
#include <sstream>
using namespace std;
class Streamer // class for one line string generation
{
public:
Streamer& clear() // clear content
{
ss.str(""); // set to empty string
ss.clear(); // clear error flags
return *this;
}
template <typename T>
friend Streamer& operator<<(Streamer& streamer,T str); // add to streamer
string str() // get current string
{ return ss.str();}
private:
stringstream ss;
};
template <typename T>
Streamer& operator<<(Streamer& streamer,T str)
{ streamer.ss<<str;return streamer;}
Streamer streamer; // make this a global variable
class MyTestClass // just a test class
{
public:
MyTestClass() : data(0.12345){}
friend ostream& operator<<(ostream& os,const MyTestClass& myClass);
private:
double data;
};
ostream& operator<<(ostream& os,const MyTestClass& myClass) // print test class
{ return os<<myClass.data;}
int main()
{
int i=0;
string s1=(streamer.clear()<<"foo"<<"bar"<<"test").str(); // test strings
string s2=(streamer.clear()<<"i:"<<i++<<" "<<i++<<" "<<i++<<" "<<0.666).str(); // test numbers
string s3=(streamer.clear()<<"test class:"<<MyTestClass()).str(); // test with test class
cout<<"s1: '"<<s1<<"'"<<endl;
cout<<"s2: '"<<s2<<"'"<<endl;
cout<<"s3: '"<<s3<<"'"<<endl;
}
You may use this header for this regard: https://github.com/theypsilon/concat
using namespace concat;
assert(concat(1,2,3,4,5) == "12345");
Under the hood you will be using a std::ostringstream.
If you are willing to use c++11 you can utilize user-defined string literals and define two function templates that overload the plus operator for a std::string object and any other object. The only pitfall is not to overload the plus operators of std::string, otherwise the compiler doesn't know which operator to use. You can do this by using the template std::enable_if from type_traits. After that strings behave just like in Java or C#. See my example implementation for details.
Main code
#include <iostream>
#include "c_sharp_strings.hpp"
using namespace std;
int main()
{
int i = 0;
float f = 0.4;
double d = 1.3e-2;
string s;
s += "Hello world, "_ + "nice to see you. "_ + i
+ " "_ + 47 + " "_ + f + ',' + d;
cout << s << endl;
return 0;
}
File c_sharp_strings.hpp
Include this header file in all all places where you want to have these strings.
#ifndef C_SHARP_STRING_H_INCLUDED
#define C_SHARP_STRING_H_INCLUDED
#include <type_traits>
#include <string>
inline std::string operator "" _(const char a[], long unsigned int i)
{
return std::string(a);
}
template<typename T> inline
typename std::enable_if<!std::is_same<std::string, T>::value &&
!std::is_same<char, T>::value &&
!std::is_same<const char*, T>::value, std::string>::type
operator+ (std::string s, T i)
{
return s + std::to_string(i);
}
template<typename T> inline
typename std::enable_if<!std::is_same<std::string, T>::value &&
!std::is_same<char, T>::value &&
!std::is_same<const char*, T>::value, std::string>::type
operator+ (T i, std::string s)
{
return std::to_string(i) + s;
}
#endif // C_SHARP_STRING_H_INCLUDED
Something like this works for me
namespace detail {
void concat_impl(std::ostream&) { /* do nothing */ }
template<typename T, typename ...Args>
void concat_impl(std::ostream& os, const T& t, Args&&... args)
{
os << t;
concat_impl(os, std::forward<Args>(args)...);
}
} /* namespace detail */
template<typename ...Args>
std::string concat(Args&&... args)
{
std::ostringstream os;
detail::concat_impl(os, std::forward<Args>(args)...);
return os.str();
}
// ...
std::string s{"Hello World, "};
s = concat(s, myInt, niceToSeeYouString, myChar, myFoo);
Based on above solutions I made a class var_string for my project to make life easy. Examples:
var_string x("abc %d %s", 123, "def");
std::string y = (std::string)x;
const char *z = x.c_str();
The class itself:
#include <stdlib.h>
#include <stdarg.h>
class var_string
{
public:
var_string(const char *cmd, ...)
{
va_list args;
va_start(args, cmd);
vsnprintf(buffer, sizeof(buffer) - 1, cmd, args);
}
~var_string() {}
operator std::string()
{
return std::string(buffer);
}
operator char*()
{
return buffer;
}
const char *c_str()
{
return buffer;
}
int system()
{
return ::system(buffer);
}
private:
char buffer[4096];
};
Still wondering if there will be something better in C++ ?
In c11:
void printMessage(std::string&& message) {
std::cout << message << std::endl;
return message;
}
this allow you to create function call like this:
printMessage("message number : " + std::to_string(id));
will print : message number : 10
you can also "extend" the string class and choose the operator you prefer ( <<, &, |, etc ...)
Here is the code using operator<< to show there is no conflict with streams
note: if you uncomment s1.reserve(30), there is only 3 new() operator requests (1 for s1, 1 for s2, 1 for reserve ; you can't reserve at constructor time unfortunately); without reserve, s1 has to request more memory as it grows, so it depends on your compiler implementation grow factor (mine seems to be 1.5, 5 new() calls in this example)
namespace perso {
class string:public std::string {
public:
string(): std::string(){}
template<typename T>
string(const T v): std::string(v) {}
template<typename T>
string& operator<<(const T s){
*this+=s;
return *this;
}
};
}
using namespace std;
int main()
{
using string = perso::string;
string s1, s2="she";
//s1.reserve(30);
s1 << "no " << "sunshine when " << s2 << '\'' << 's' << " gone";
cout << "Aint't "<< s1 << " ..." << endl;
return 0;
}
Stringstream with a simple preproccessor macro using a lambda function seems nice:
#include <sstream>
#define make_string(args) []{std::stringstream ss; ss << args; return ss;}()
and then
auto str = make_string("hello" << " there" << 10 << '$');
This works for me:
#include <iostream>
using namespace std;
#define CONCAT2(a,b) string(a)+string(b)
#define CONCAT3(a,b,c) string(a)+string(b)+string(c)
#define CONCAT4(a,b,c,d) string(a)+string(b)+string(c)+string(d)
#define HOMEDIR "c:\\example"
int main()
{
const char* filename = "myfile";
string path = CONCAT4(HOMEDIR,"\\",filename,".txt");
cout << path;
return 0;
}
Output:
c:\example\myfile.txt
Have you tried to avoid the +=?
instead use var = var + ...
it worked for me.
#include <iostream.h> // for string
string myName = "";
int _age = 30;
myName = myName + "Vincent" + "Thorpe" + 30 + " " + 2019;