How can I re-define + operator? [duplicate] - c++

This question already has answers here:
Can we overload operators for built-in types like int or float?
(3 answers)
Closed 7 years ago.
I would like to re-define
+
operator.
So, I make a simple code like below code.
int operator+(const int &a, const int &b)
{
int temp = a-b;
return temp;
}
int main()
{
int a = 10;
int b = 5;
cout << a+b << endl;
}
I can re-define with Class type... But I don't want to use Class.
How can I resolve this issue?

You cannot define the operators for plain old data types like int.
You could build your own int class (my_int, say) and include the line #define int my_int. But this would be extremely pernicious and wouldn't work with compile-time evaluated literal expressions.

You cannot redefine operator for int (or any other built in type).
If you say, what do you want to do, we might find some solution.

Related

"no instance of function template matches the argument list" : Compiler passing pointer as size_t and size_t as int [duplicate]

This question already has answers here:
How to create an object in a form like this: ifstream in();
(1 answer)
Trying to understand default constructors and member initialisatioon
(3 answers)
What is the purpose of the Most Vexing Parse?
(6 answers)
Is most vexing parse a formally defined concept
(2 answers)
Closed 3 months ago.
I have this concept and template function
template<typename T>
concept Averageable = std::is_default_constructible<T>::value &&
requires(T a, T b)
{
{ a += b } -> std::convertible_to<T>;
{a / size_t(1)} -> std::convertible_to<T>;
};
template<typename T>
requires Averageable<T>
T mean(const T* vals, size_t size)
{
T sum();
for (size_t i{}; i < size; size++)
{
sum += vals[i];
}
return sum / size;
}
And for some reason calling like this
const int a[]{1,2,3};
const int res = mean<int>(a, 3);
results in the following IntelliSense error
no instance of function template matches the argument list argument types are: (size_t, int)
I'm using Visual Studio 2022 with c++ 20. I have tried searching for a reason why this is happening endlessly (as well as a proper tutorial for concepts) and have come up short.
I'm new to using concepts/requires so if anyone has any insight as to why this doesn't work or how to properly do it I would greatly appreciate it
Your concept/require is fine. The problem you got here is actually most vexing parse. Namely this line:
T sum();
Despite it might look like you are constructing an integer, it's actually declaring a function that returns a T.
To fix it, simply change the parentheses to braces:
T sum{};
Sidenote, in the for loop, you probably wanted i++ instead of size++.

What does return a,b do and why? [duplicate]

This question already has answers here:
How does the Comma Operator work
(9 answers)
Closed 6 years ago.
When we use "return 4,5" in c++ it does not give error but instead returns 5 (at least 4 would be understandable as it should return the first number it encounters) . Why does this happen and can we use this to return 2 values in any way?
Here is the code that i tried
#include<iostream>
using namespace std;
int something()
{
return 4,5;
}
int main()
{
int a=0,b=0;
a,b = something();
cout<<a<<b<<endl;
}
also in the above code for some reason 5 is assigned to b instead of a
This is how comma operator works - it evaluates all the operands and returns the last one.
Unfortunately, C++ does not have built-in tuple (like int, double, etc.) type, so, it is impossible to return more than one value from the function. However, you could use wrapper type std::tuple and then unpack it using std::tie function:
#include <iostream>
#include <tuple>
std::tuple<int, int> something()
{
return {1, 2};
}
int main()
{
int a=0, b=0;
std::tie(a, b) = something();
std::cout << a << b << std::endl;
}
This is a little bit overhead for two variables, though.
It's using the built-in comma operator (since these are not user defined types). For user defined types it would be calling operator,() (the comma operator).
The comma operator evaluates both sides of the operator and returns the result of the latter. Which is why you get 5 and not 4 as the result.
As to why it is done here I cannot say - seems silly.
If you want to return two values, return a std::vector with them. Maybe a std::pair, or a class. As far as why, this is just how C++ works. Comma is just an operator, like + or -. It discards its left operand and returns the right one. return returns the value of its expression from the function. The rest you can figure out yourself.

what's the difference between these two pointer code [duplicate]

This question already has answers here:
Pointer vs. Reference
(12 answers)
Closed 6 years ago.
I found these two different sources, but they do the exact same thing. I was wondering if there is a difference or not but I couldn't figure it out.
Can anyone tell me the difference and when should I use which?
this is the first one:
void function1(int *x) {
*x = 100;
}
int main() {
int var1 = 10;
function1(&var1);
cout << var1 << endl;
}
and this is the second one:
void function2(int &x) {
x = 100;
}
int main() {
int var2 = 10;
function2(var2);
cout << var2 << endl;
}
int *x is a pointer whereas int &x is a reference. Probably the biggest difference is that you can't change where reference is pointing to.
The first is a pointer, the second is a reference. The ideas have some similarities, but there are also differences.
A pointer is a C and C++ mechanism and a bit more "pure" but gives you more posibilies for advanced concepts like pointer arithmetics. References are C++ only and are more safe and more implicit, as a reference is used with the same syntax as a normal varible while using the referenced one. A pointer is more explicit if you want to use or change its value, as you have to explicitely dereference it using *var, and explicitely have obtain it.

putting a '&' after the type [duplicate]

This question already has answers here:
ampersand (&) at the end of variable etc
(5 answers)
Closed 3 years ago.
I am fairly new to programming. I am just moving on to C++ from C in my college courses, and I encountered something that I haven't seen before in C. Sometimes after the type, either in a function declaration or passing a parameter, a & immediately follows the type. For example, we use a struct called Customer in one of our projects, and some of the functions pass Customer&. Why is the ampersand after the type, as opposed to in front? Thanks!
References in C++ simply allow for a cleaner way to execute the following code:
int x = 16;
int* y = &x;
cout << *y;
Which could be written instead as
int x = 16;
int& y = x;
cout << y;
When defining functions, a reference allows a function to change the value of parameters without causing the user of the function to put an ampersand before everything. E.g.
void func( int& a )
{
a = 5;
}
void main()
{
int A = 10;
func( A );
cout << A; // Will output '5'
}
Be careful with this type of mutation, as a programmer using functions like this without checking the implementation might not realize that the function is changing the value of the parameters unless the intent is obvious. init_server(my_server) would be an example of a case where it's obvious, but to_json(my_struct) would clearly be an example where you should not be using a reference to change the struct in any way.
But, one of the most important uses of references, would be function like
int sum_vector( const vector<int>& a ) {
int sum = 0;
for( int i = 0; i < a.size(); i++ ) {
sum += a[i];
}
return sum;
}
If you tried to make sum_vector take in a vector, and you passed in a vector with 100 million entries, then it would have to copy them all over, taking forever. You could take in a pointer, but then the internal parts of the function would have to constantly dereference, and it must called with sum_vector(&myvec), which is more annoying than sum_vector(myvec). In this way, using a const reference, you can prevent the highly inefficient copying of the whole vector into the function body, while keeping syntax neat. Using const lets you reassure yourself that you're not going to change the vector that you were given. And, it also assures the user of your function that you won't change it. Similarly, void to_json(const some_struct&) would be a better function definition as it ensures you won't change the user's data.

Initialization of const array in C++ [duplicate]

This question already has answers here:
initialize a const array in a class initializer in C++
(10 answers)
Closed 9 years ago.
I need to initialize a const int array in a class constructor via initialization list in C++.
I know that there is an easy solution of this problem based on using
extended initialization list.
Still, I want to avoid using -std=c++11 or -std=gnu++11.
Obviously, I know from the beginning that its size is 4 and the
content is {1, 2, 3, 4}.
The only way I can conceive doing this while staying out of the C++11 initializer list realm is to bury it in a struct wrapper and value-initialize it in your construct-initializer list:
#include <iostream>
using namespace std;
struct ArrayWrap
{
int content[4];
int& operator [](size_t n) { return content[n]; }
int operator [](size_t n) const { return content[n]; }
};
static const ArrayWrap content = { {1,2,3,4} };
struct MyObj
{
const ArrayWrap arrwrap;
MyObj() : arrwrap(content) {}
};
int main(int argc, char *argv[])
{
MyObj obj;
for (int i=0;i<4;++i)
cout << obj.arrwrap[i] << ' ';
cout << endl;
return EXIT_SUCCESS;
}
Output
1 2 3 4
It is common in C to bury fixed arrays in structures when returning them from functions by value, and in this case I'm simply exploiting the default copy-ctor of the wrapper struct as-generated by the C++ compiler.
Probably not the ideal solution for what you want, but it does work, and compiles under C++98.
Well, if you're banning C++11 solutions from the candidate set, then you simply cannot do this.