#include <iostream>
usingnamespace std;
struct Int{ int x; };
intoperator +( Int a, Int b ){ return a.x + b.x; }
int main()
{
// Why can I do this for a user-defined type ...
int (*f)( Int, Int ) = operator + ;
Int a{ 3 };
Int b{ 4 };
cout << f( a, b ) << '\n';
// ... but I can't do this for a built-in type ?
// int (*g)( int, int ) = operator + ;
// cout << g( 3, 4 ) << '\n';
}
For built-in types you don't have such a [user-defined] function
Does this mean that for built-in types there is no built-in function that carries out the addition operation in the same way as I would define for a user type? I'm curious, because with template programming I have hitherto defined functions for a general type T, irrespective of whether it were built-in or user-defined: I've seen no distinction ... until I get to these fundamental operators.
There are no functions involved in standard operations on built in types.
For example:
1 2 3 4 5 6 7 8 9 10 11 12
struct Int { int x ; };
Int& operator++( Int& i ) { ++i.x ; return i ; }
int main()
{
Int a{4} ;
++a + ++a ; // no undefined behaviour here (functions, ergo indeterminately sequenced)
int b{4} ;
++b + ++b ; // this is undefined behaviour (unsequenced modifications to b)
}
Standard function objects (eg. std::plus) provide uniform interfaces to common arithmetic and logical operators.
For instance:
Mmm, I had been doing that, @Peter. I was just hoping to circumvent it by using
operator +
rather than having to define another function, lambda or otherwise.
It seems that standard/built-in types don't work in the same way as I had been (mistakenly) expecting.
Does this mean that for built-in types there is no built-in function that carries out the addition operation in the same way as I would define for a user type?
Correct. The point is that the compiler needs to generate processor instruction at one point.
If
intoperator+ ( int i, int j )
where allowed how could the compiler ever produce these processor instructions?