I realized this is wrong but I could not delete it - c++

Author: This of course can not be done. Learn from the answers below.
In C++ how do we do the following
// fundamental language construct
type name = value ;
// for example
int x = y;
with function pointers?
typedef (char)(*FP)(unsigned);
// AFAIK not possible in C++
FP x = y ;
I can use lambdas:
FP x = []( unsigned k) -> char { return char(k); }
But I do not know how to do this without the lambda. Any ideas?

Whenever you can write a typedef, you can also write a variable declaration with no typedef, with almost identical syntax.
Example:
// typedef
typedef char(*FP)(unsigned);
FP x = y ;
// no typedef
char(*x)(unsigned) = y;
Remove the typedef keyword, and you have a variable declaration. Slap an initialisation on it if you want.

You can use auto:
auto fptr = &f;
It skips the need of a typedef and conserve a nice syntax.

It is almost the same as Lambdas, but hard to read i think:
void my_int_func(int x)
{
std::cout << "ther param is: " << x << std::endl;
}
//
int main(int argc, char *argv[])
{
void (*foo)(int) = my_int_func;
foo(1);

But I do not know how to do this without lambda. Any ideas?
Just dont use a lambda but a function:
typedef char(*FP)(unsigned);
char foo(unsigned){ return 0;}
int main() {
FP x = foo;
}
Function pointer typedefs are rather nasty, if you can better use using:
using FP = char(*)(unsigned);
Live Demo

Well... if you're using lambdas, you can also use auto, so
auto x = foo;
The following is a full compiling example with a static_assert() that verify the obtained type
#include <type_traits>
char foo (unsigned)
{ return ' '; }
int main ()
{
auto x = foo;
static_assert( std::is_same<decltype(x), char(*)(unsigned)>::value, "!" );
}
Using auto with lambda in the way you used it with FP
auto y = []() ->bool { return true; };
leads to something different: the type of y above is an unnamed class with an operator(), not a function pointer type to that operator().
If you want a pointer to function, you have to convert the lambda to it using the operator +, as you can verify with the following static_assert()
auto y = +[]() ->bool { return true; };
static_assert( std::is_same<decltype(y), bool(*)()>::value, "!" );

Many thanks all for the lively roller-coaster of useful comments. Somebody on Reddit, where I asked the same question, under the user name "TheTiefMaster", dropped this "one liner":
// also works as C
char whatever(unsigned k) { return char(k); } char(*F)(unsigned) = whatever;
Let me clarify: I do understand these are two statements on one line. And no there is no type in here, but one function pointer pointing to the same function. The usage:
auto x = whatever(65); // 'A'
auto y = F(66); // 'B'
Then I figured the following will make the function definition and its type declaration:
// FP is a type of function whoever
char whoever(unsigned k) { return 'A'; } typedef char(*FP)(unsigned) ;
Calling whoever behaves as expected
auto w = whoever(42) ; // 'A'
FP is where it starts getting interesting. FP is a type, and as it turns out one can cast to the type.
// using FP as a type
// c++ style type cast
// empty cast returns nullptr
auto fun = FP();
// calling fun() above crashes
// but it is "invocable" as per C++ rules
static_assert(std::is_invocable_v<P2F()>);
Passing any argument to this cast, works and returns non null address:
// update: this compiles only on MSVC
// and is a bug
auto fun = FP(42);
// type of fun is char (*) (unsigned)
Calling the result of this fun crashes, obviously:
// reading access violation
fun(123) ;
This cast with an instance from any required function, works:
auto fun = FP(whatever);
// works, obviously
fun(65) ; // 'A'
To use this knowledge we will use the static_cast to safely cast to what we can call. C++ type cast is too forceful, just like C style type cast is.
// does not compile
// fun is the wrong type and can not be called
auto fun = static_cast<FP>(42);
// does compile, fun is safe to call
auto fun = static_cast<FP>(whatever);
// works, obviously
fun(65) ; // 'A'
This investigation is obviously far from over. I shall proceed with it, elsewhere.
Update:
using FP = char (*)(int) ;
// must not compile, compiles under MSVC
auto oops = FP(42) ;
Is the bug in MSVC, I reported it today.

The code:
typedef char(*FP)(int);
FP x = y;
fails to compile with current C++ compilers if y is a lambda expression capturing a variable.
// Compiles OK
FP x0 = [](int k) -> char { return char(k); };
// Fails to compile
int i = 123;
FP x1 = [=](int k) -> char { return char(k); };
FP x2 = [=](int k) -> char { return char(k+i); };
FP x3 = [&](int k) -> char { return char(k+i); };
FP x4 = [i](int k) -> char { return char(k+i); };
// error: cannot convert ‘main()::<lambda(int)>’ to ‘FP {aka char (*)(int)}’
// in initialization
The reason why it fails to compile is that the size of the right side of the assignment to x1...x4 is greater than size of FP.
For a C++ compiler to make assignments to x1...x4 be valid it would need to generate code at runtime. Current C++ compilers such as GCC and clang do not support this, mainly because it would cause memory leaks because C++ isn't a garbage collected language. Some garbage collected language implementations, such as earlier versions of the official Go compiler, do support such assignments by performing runtime code generation.

Related

Why does the following result in segmentation fault?

const int* additional(int* s, int* f){
const int* ts = reinterpret_cast<const int*>(*s + *f);
return ts;
}
int main() {
int a = 10, b = 20;
const int* oc = additional(&a, &b);
std::cout << *oc;
return 0;
}
I've tried using static, although it produces the same error
There are many things wrong with your code.
*s + *f is an int, not a pointer (you add the dereferenced values).
you are doing a reinterpret cast which isn't needed at all. Just pass the int's directly without pointers and you are good to go.
const int additional(int s, int f){
return s + f;
}
int main() {
int a = 10, b = 20;
const int oc = additional(a, b);
std::cout << oc;
return 0;
}
You reinterpret the number 30 as a pointer to const int and attempt to read through the reinterpreted pointer. The operating system noticed that the process was attempting to access an address wasn't mapped for the process and sent the segfault signal to terminate the process in order to protect the badly behaving process from itself.
Reinterpret casting is unsafe. Don't use it unless you know what you're doing. And when you know what you're doing, you'll know that it's quite rare to need to use it.
I was aiming to shorten the int t = *f + *s;
That is already extremely short. The function that you defined is much longer and so is even a call to the function. Note that the initialiser expression that you quote has type int while your function returns const int*. That, along with the broken reinterpret cast are the problem.
If you wanted to make the indirection shorter, then how about using references instead of pointers:
const int& f = a;
const int& s = b;
int t = a + b; // shorter

creating a literal for a Point - C++

I am trying to do a simple library where the object is a point on the xy-axis.
I want to be able to use literals like this:
Point a = (3,4);
where (3,4) is a point literal.
I read about user defined literals, but (as I understood) this seems to be impossible.
May be "(3,4)"_P is possible as I understand it.
However, I found on this page interesting use of user defined literals as follows:
#include <iostream>
#include <complex>
int main()
{
using namespace std::complex_literals;
std::complex<double> c = 1.0 + 1i;
std::cout << "abs" << c << " = " << abs(c) << '\n';
}
I can under stand the part 1i as a user defined literal, but not the whole thing 1.0 + 1i.
What I am missing, and what is the nearest possible way of getting a literal similar to (x,y) without using ".
As Some programmer dude shows, the best way is to use uniform initialization.
However, just for the fun of it, you can (sort of) do this with User Defined Literals. My idea is to to have 2 literals for each coordinate and overload operator+ between them to create the point.
Remember, this is just for fun, don't use this in a real code:
struct Px { int x; };
struct Py { int y; };
struct Point {
int x;
int y;
};
constexpr auto operator""_px(unsigned long long x) -> Px { return Px{(int)x}; }
constexpr auto operator""_py(unsigned long long y) -> Py { return Py{(int)y}; }
constexpr auto operator+(Px x, Py y) -> Point { return Point{x.x, y.y}; }
then you can have:
auto p = 3_px + 4_py; // p is deduced to type `Point`
Of course this is just a rough framework. Read this great article to learn more about UDLs. You would need to deal with the narrowing conversion in a better way and propper use namespaces to make it a better solution.
As a bonus, you could also use operator, to create a syntax more appropriate to what you had in mind. But, don't do this, as overloading operator, is just evil:
auto operator,(Px x, Py y) -> Point { return Point{x.x, y.y}; }
auto p = (2_px, 1_py); // p is deduced to type `Point`
You can't make up literals on your own, only create suffixes for literals. Like the shown 1i or the standard language f as in 1.0f. (See e.g. this user-defined literal reference for more information.)
What you can to is to use uniform initialization doing something like
Point a = { 3, 4 }; // note the use of curly-braces
Depending on what Point is you might need to add a suitable constructor to make it work.
You have 3 options
Point p = { 1,2 };
Point p2{ 1,2 };
Point p3(1,2);

variable declaration in function return type specifier c++type

I was trying out codefights.com and noticed someones answer to a question which involved giving all the longest strings in a vector do this:
std::vector<std::string> r, allLongestStrings(std::vector<std::string> a) {
int b=0;
for (s:a) if (s.size()>b) b=s.size();
for (s:a) if (s.size()==b) r.push_back(s);
return r;
}
He's declaring a variable in the return type specifier for the function, can anyone tell me why this is allowed? I't doesn't compile on my machine and I couldn't find a gcc extension that does this, thanks in advance :).
Looking at the reference (decl-specifier-seq), I don't see how it would be possible to declare the return variable before the function name.
With C++14, you can use the auto keyword to remove the duplicate mentioning of the return type:
auto allLongestStrings( const std::vector<std::string>& a ) {
std::vector<std::string> r;
std::size_t b = 0;
for( const auto& s : a ) if( s.size() > b ) b = s.size();
for( const auto& s : a ) if( s.size() == b ) r.push_back( s );
return r;
}
I fixed some other things of the code:
to improve efficiency, declare the parameter a as const reference, so it won't be copied
declare b as std::size_t to match return type of std::vector::size()
in range-for loop, a type specifier is necessary (even if it is auto); added const reference for efficiency
Live demo.
The mixed variable / function declaration seems to be ok, though gcc complains that function definition shouldn't be there but I think it's ok at global scope. But it's a 100% valid syntax even in non-global scope if no function definition is given. This declaration is just regular declarations of several items of the same leading type. For example we can declare multiple items of different kinds but with same leading like this:
// single line declaration
int i = 0, * p_i = nullptr, ai[2] = {42,42}, geti(void), * * getppi(void);
// the same as
int i = 0;
int * p_i = nullptr;
int ai[2] = {42, 42};
int geti(void);
int ** getppi(void);
So r is just a regular variable of type std::vector<std::string>, followed by function allLongestStrings that returns the same std::vector type.
This compact declaration form exists for historical reasons. Basically it helped to save quite some bytes for storing and compiling the source file.
This form of for loop is probably on of the earlier experimental extensions before current form was standardized.

Composite function in C++

I am a beginner in C++ and want to do simple example of composite function.
For example, in MATLAB, I can write
a = #(x) 2*x
b = #(y) 3*y
a(b(1))
Answer is 6
I searched following questions.
function composition in C++ / C++11 and
Function Composition in C++
But they are created using advanced features, such as templates, to which I am not much familiar at this time. Is there a simple and more direct way to achieve this? In above MATLAB code, user does not need to know implementation of function handles. User can just use proper syntax to get result. Is there such way in C++?
** Another Edit:**
In above code, I am putting a value at the end. However, if I want to pass the result to a third function, MATLAB can still consider it as a function. But, how to do this in C++?
For example, in addition to above code, consider this code:
c = #(p,q) a(p)* b(q) %This results a function
c(1,2)
answer=12
d = #(r) a(b(r))
d(1)
answer=6
function [ output1 ] = f1( arg1 )
val = 2.0;
output1 = feval(arg1,val)
end
f1(d)
answer = 12
In this code, c takes two functions as input and d is composite function. In the next example, function f1 takes a function as argument and use MATLAB builtin function feval to evaluate the function at val.
How can I achieve this in C++?
How about:
#include <iostream>
int main(int, char**)
{
auto a = [](int x) { return 2 * x; };
auto b = [](int y) { return 3 * y; };
for (int i = 0; i < 5; ++i)
std::cout << i << " -> " << a(b(i)) << std::endl;
return 0;
}
Perhaps I'm misunderstanding your question, but it sounds easy:
int a(const int x) { return x * 2; }
int b(const int y) { return y * 3; }
std::cout << a(b(1)) << std::endl;
Regarding your latest edit, you can make a function return a result of another function:
int fun1(const int c) { return a(c); }
std::cout << fun1(1) << std::endl;
Note that this returns a number, the result of calling a, not the function a itself. Sure, you can return a pointer to that function, but then the syntax would be different: you'd have to write something like fun1()(1), which is rather ugly and complicated.
C++'s evaluation strategy for function arguments is always "eager" and usually "by value". The short version of what that means is, a composed function call sequence such as
x = a(b(c(1)));
is exactly the same as
{
auto t0 = c(1);
auto t1 = b(t0);
x = a(t1);
}
(auto t0 means "give t0 whatever type is most appropriate"; it is a relatively new feature and may not work in your C++ compiler. The curly braces indicate that the temporary variables t0 and t1 are destroyed after the assignment to x.)
I bring this up because you keep talking about functions "taking functions as input". There are programming languages, such as R, where writing a(b(1)) would pass the expression b(1) to a, and only actually call b when a asked for the expression to be evaluated. I thought MATLAB was not like that, but I could be wrong. Regardless, C++ is definitely not like that. In C++, a(b(1)) first evaluates b(1) and then passes the result of that evaluation to a; a has no way of finding out that the result came from a call to b. The only case in C++ that is correctly described as "a function taking another function as input" would correspond to your example using feval.
Now: The most direct translation of the MATLAB code you've shown is
#include <stdio.h>
static double a(double x) { return 2*x; }
static double b(double y) { return 3*y; }
static double c(double p, double q) { return a(p) * b(q); }
static double d(double r) { return a(b(r)); }
static double f1(double (*arg1)(double))
{ return arg1(2.0); }
int main()
{
printf("%g\n", a(b(1))); // prints 6
printf("%g\n", c(1,2)); // prints 12
printf("%g\n", d(1)); // prints 6
printf("%g\n", f1(d)); // prints 12
printf("%g\n", f1(a)); // prints 4
return 0;
}
(C++ has no need for explicit syntax like feval, because the typed parameter declaration, double (*arg1)(double) tells the compiler that arg1(2.0) is valid. In older code you may see (*arg1)(2.0) but that's not required, and I think it makes the code less readable.)
(I have used printf in this code, instead of C++'s iostreams, partly because I personally think printf is much more ergonomic than iostreams, and partly because that makes this program also a valid C program with the same semantics. That may be useful, for instance, if the reason you are learning C++ is because you want to write MATLAB extensions, which, the last time I checked, was actually easier if you stuck to plain C.)
There are significant differences; for instance, the MATLAB functions accept vectors, whereas these C++ functions only take single values; if I'd wanted b to call c I would have had to swap them or write a "forward declaration" of c above b; and in C++, (with a few exceptions that you don't need to worry about right now,) all your code has to be inside one function or another. Learning these differences is part of learning C++, but you don't need to confuse yourself with templates and lambdas and classes and so on just yet. Stick to free functions with fixed type signatures at first.
Finally, I would be remiss if I didn't mention that in
static double c(double p, double q) { return a(p) * b(q); }
the calls to a and b might happen in either order. There is talk of changing this but it has not happened yet.
int a(const int x){return x * 2;}
int b(const int x){return x * 3;}
int fun1(const int x){return a(x);}
std::cout << fun1(1) << std::endl; //returns 2
This is basic compile-time composition. If you wanted runtime composition, things get a tad more involved.

What does the following C++statement mean

There is a statement I saw in an C++ interview test today:
int (*(*fb)(int, char*))[2];
I have no idea what this declaration could mean. It looks much like function pointer but first star and square braces spoil everything.
Visual Studio decodes fb's type as following int[2] * (int, char *) *, which still looks like a bit cryptic.
If we simplify declaration than everything looks clear
int(*(*fa)(int, char*));
int* func(int, char*)
{
return 0;
}
// now we can assign func to fa
fa = func;
Any ideas?
fb is a function pointer of the following signature:
The function takes two parameters: int and char*
The function returns a pointer to an array of two int, which has the type int(*)[2]
Usually, because of the cryptic syntax of function pointers, array pointers and such stuff, you should use typedefs or type aliases (the new using-syntax) to make it clearer step by step:
using int2 = int[2];
using int2ptr = int2*;
using fb = int2ptr(int, char*);
Proof
Also, instead of returning arrays, you could consider returning a std::vector or std::array; instead of passing char pointers you could consider std::string, and instead of using function pointers you could consider std::function. All these are "coulds", since every "raw type" has its reason to exist, but the reasons are very limited.
It is a definition of pointer to function that has two parameters, one of type int and other of type char *, and returns pointer to array of type int[2].
Here is a simplified demonstrative program. I have only changed the second parameter to type const char *
#include <iostream>
int(*f( int x, const char *s ))[2]
{
static int a[2] = { x, *s };
return &a;
}
int main()
{
int (*(*fb)(int, const char*))[2] = f;
auto p = fb( 10, "A" );
std::cout << ( *p )[0] << '\t' << ( char )( *p )[1] << std::endl;
return 0;
}
The output is
10 A
Colleague of mine have just sent an answer:
int (*(*fb)(int, char*))[2];
int(*(returnArray(int, char*)))[2]
{
static int tab[2];
return &tab;
}
// finally we have it
fb = returnArray;
I have no idea who can use this and for what purpose