Overloading conversion operator from int to std::string [duplicate] - c++

This question already has answers here:
Converting an int to std::string
(11 answers)
Closed 5 years ago.
Is it possible to overload conversion operator from int to std::string? Is it possible to use this function:
void printToLog(std::string text);
Like this:
int a = 5;
printToLog(a);
Or this:
int a = 5;
printToLog(a + " bombs have been planted.");
?

There's a function for it in the standard library. The aptly named std::to_string:
int a = 5;
printToLog(std::to_string(a) + " bombs have been planted.");
You cannot add a conversion operator for this purpose. Such an operator can only be a member of a class type, and int is not a class type. Neither can you add a converting constructor to std::string. Use the mechanism the standard gives you.

Related

c++ the difference between string using the assign function and directly using '=' to change the value [duplicate]

This question already has answers here:
std::string::assign vs std::string::operator=
(2 answers)
Closed 2 years ago.
For example, this code
std::string a("this is a string");
std::string b;
b = a;
std::string c;
c.assign(a);
Is there any difference between B and C in essence?
From cppreference
2) basic_string& assign( const basic_string& str );
...
2) Replaces the contents with a copy of str. Equivalent to *this = str;. In particular, allocator propagation may take place. (since C++11)
So this does the same.

static_cast<type>() vs type () [duplicate]

This question already has answers here:
Regular cast vs. static_cast vs. dynamic_cast [duplicate]
(8 answers)
C++ cast syntax styles
(10 answers)
Closed 4 years ago.
In the "Programming: Principles and Practice Using C++", "Section 8.5.7 Argument checking and conversion" the following example is given as evidence on how to properly convert types, but never clearly explains why you would use int() vs static_cast<int>() to convert from a double to an int. However, I'm still unclear on the benefits of static_cast<int>() vs int().
void ff(int x);
void gg(double y) {
ff(y); // how would you know if this makes sense?
int x=y; //how would you know if this makes sense?
}
void ggg(double x) {
int x1 = x; // truncate x
int x2 = int(x);
int x3 = static_cast<int>(x); // very explicit conversion (17.8)
ff(x1);
ff(x2);
ff(x3);
ff(x); // truncate x
ff(int(x));
ff(static_cast<int>(x)); // very explicit conversion (17.8)
}
I checked section 17.8, but still didn't find clarity on this topic. Can someone help? I'm looking for a solution that compares static_cast with function-style cast.
Explicit type conversion is permissive [expr.type.conv]:
If the initializer is a parenthesized single expression, the type conversion expression is equivalent to the corresponding cast expression.
On the other-hand if you use it only for fundamental types it should be fine. It should be never used in generic code:
template<class T,class...Args>
auto dangerous_construct(Args...args){
return U(args...); //here we could have a reinterpret_cast
}
int i;
double* v = dangerous_build<double*>(&i);//no compilation error!
If you look for a short and safe cast use the brace-style:
template<T,class...Args>
auto safe_construct(Args...args){
return U{args...}; //OK equivalent to a static_cast + narrowing checks.
}

Is there any advantage of using std::addressof() function template instead of using operator& in C++? [duplicate]

This question already has answers here:
When to use addressof(x) instead of &x?
(5 answers)
Closed 7 years ago.
If addressof operator& works well then why C++ has introduced addressof() function? The & operator is part of C++ from the beginning - why this new function is introduced then? Does it offer any advantages over C's & operator?
The unary operator& might be overloaded for class types to give you something other than the object's address, while std::addressof() will always give you its actual address.
Contrived example:
#include <memory>
#include <iostream>
struct A {
A* operator &() {return nullptr;}
};
int main () {
A a;
std::cout << &a << '\n'; // Prints 0
std::cout << std::addressof(a); // Prints a's actual address
}
If you wonder when doing this is useful:
What legitimate reasons exist to overload the unary operator&?

C++ implicit conversion: Why should literal string convert to string? [duplicate]

This question already has answers here:
C++ implicit conversions
(4 answers)
Closed 7 years ago.
The example is from Chapter 7 in C++ Primer 5th.
Suppose class Sales_data has such constructor:
Sales_data(const std::string &s): bookNo(s) { }
And it has a public function member:
Sales_data &combine(Sales_data &s){...}
The flowing is error:(item is a Sales_data instance)
item.combine("9-999-9999");
The reason is that: Only One Class-Type Conversion Is Allowed, however, the code mentioned above has two user-defined conversions.
"9-999-9999" to string
string to Sales_data
Why should literal string convert to string ? Is 9-999-9999 not a string ?
"9-999-9999" is not a string, it is a const char[]. You can fix this by adding a constructor to you class that takes a const char * like:
Sales_data(const char* s): bookNo(s) { };
If you have C++14 support than you could also use a std::string_literal:
item.combine("9-999-9999"s);

What does this warning mean in orwell dev C++ IDE? [duplicate]

This question already has answers here:
Default constructor with empty brackets
(9 answers)
Closed 8 years ago.
I recently wrote below simple program but compiler shows warning.
#include <iostream>
int main()
{
int a();
std::cout<<a;
return 0;
}
[Warning] the address of 'int a()' will always evaluate as 'true' [-Waddress]
What is the meaning of the above warning? Why value of a is 1 not 0?
It might look like a definition of a as an int, but:
int a();
declares a function a taking no parameters and return int.
Use:
int a{};
instead.
std::cout<<a;
calls operator<<() with bool which is always nonzero, hence true.
int a(); declares a function, not a variable. If you want a to be a zero-initialised variable, then you'll need one of
int a{}; // C++11 or later
int a = int();
int a(0);
int a = 0;
<< doesn't have an overload that can directly take a function; so it looks for a suitable conversion sequence to a type that it is overloaded for, and finds:
int() -> int(*)() -> bool
that is, using the standard function-to-pointer and pointer-to-boolean conversions. The function pointer won't be null, since a declared function must exist and have an address; so the boolean value will be true.