#include "std_lib_facilities.h"
typedefdouble F(double);
struct A
{
A() { }
A(F arg) { n = int(arg); }
int n;
};
double example_f(double) { return 1; }
int main()
{
A obj(log);
A obj2(cos);
A obj3(example_f);
cout << obj.n << "\n";
cout << obj2.n << "\n";
cout << obj3.n << "\n";
keep_window_open();
}
I particularly don't understand typedefdouble F(double);. I know the output results are erroneous. I just need someone to explain to me how this thing works. Have in mind that I am a beginner so please explain it as simple as possible (some of you might ask why am I asking such a question, well it's in the book I am reading so I want to know what it is). Thanks in advance to anyone who replies!
It is a type-id for a function declaration that has return value of the type double and one parameter of the type double.
Consider the following simple example
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
#include <iostream>
typedefdouble F(double);.
int main()
{
F my_func; // here identifier my_func is declared as having type of double( double)
std::cout << my_func( 10.0 ) << std::endl;
}
double my_func( double x )
{
return x * x;
}
A typedef just creates an alias for a type (another name by which the type can be known).
A typeid is different from a type alias.
Where would we use it? Typically, when we want to access a function indirectly through a reference or a pointer. And we want to simplify the syntax; make the code more readable.
#include <iostream>
double foo( double d ) { return d*2 ; }
double bar( double d ) { return d/2 ; }
int main()
{
typedefdouble F(double); // F is an alias for double(double)
// ie. a unary function taking a double and returning a double}
F& fn1 = foo ; // type of 'fn1' is reference to F
// ie. a reference to a unary function taking a double and returning a double}
// and it is initialized to refer to foo
std::cout << fn1(1.234) << '\n' ; // foo(1.234)
F& fn2 = bar ; // type of 'fn2' is reference to F
// ie. a reference to a unary function taking a double and returning a double}
// and it is initialized to refer to bar
std::cout << fn2(1.234) << '\n' ; // bar(1.234)
F* pfn = nullptr ; // type of 'pfn' is pointer to F
// ie. a pointer to a unary function taking a double and returning a double}
// and it is initialized to be a null pointer
pfn = &foo ; // pfn now points to foo
std::cout << (*pfn)(1.234) << '\n' ; // foo(1.234)
pfn = &bar ; // pfn now points to bar
std::cout << (*pfn)(1.234) << '\n' ; // bar(1.234)
// the above two lines can also be written as:
pfn = bar ; // pfn now points to bar - address of is implied
std::cout << pfn(1.234) << '\n' ; // bar(1.234) - dereference of pointer is implied
}