In PortAudio's C++ bindings, there is a MemFunCallBackStream constructior that can be called as:
portaudio::MemFunCallbackStream<MyClass> streamRecord(paramsRecord,
*AnInstanceOfMyClass,
&MyClass::MemberFunction);
where last parameter is the callback function. However without using the & operator on that parameter compiler fails. But as far as I know & parameter is omitable when obtaining address of functions to use in function pointers. Is this somehow different from C callback function and ptr. to func. syntax?
This FAQ seems to suggest that you can omit the & (for static member functions, at least), but then goes on to give various reasons why you shouldn't confuse ordinary function-pointers with C++ member-function-pointers.
EDIT: Found more information here, which is relevant to non-static member functions:
Some compilers (most notably MSVC 6
and 7) will let you omit the &, even
though it is non-standard and
confusing. More standard-compliant
compilers (e.g., GNU G++ and MSVC 8
(a.k.a. VS 2005)) require it, so you
should definitely put it in. To invoke
the member function pointer, you need
to provide an instance of SomeClass,
and you must use the special operator
->*. This operator has a low precedence, so you need to put it in
parentheses. [Emphasis added]
The C++ standard, in its section on Unary operators, states that a pointer-to-member requires explicit use of &.
Related
You probably know that datatypes as std::string have some functions in it.
For example std::string.substr().
I want to know, is there a way that i can add more funcionts to those types?
For example:
int a = 42;
a.isLife(); // a function that returns true if a is 42
But isLife() doesn't exist right?
Is there a way i can add it?
No, that's not possible in C++. In C++ you write isLife(a) instead.
There is no way to do so.
Primitive types are primitive, they don't have operator .available. Primitive types are not classes.
You also cannot append anything to a defined class. Once it's defined, it's complete. Otherwise, compiler wouldn't be able to use this class - what if there was one use of a non-changed class, then someone adds something to this class and uses this class. Which version is now used?
In theory, you could edit system headers like <string>, but that's very theoretical. It's against the standard and no compiler supports it AFAIK.
#SonicAsF, you cannot/should not. #MSalters have the correct answer. That is how C++ intends you to extend classes. This is why std::begin, std::end, and std::swap are what they are. This is also why argument-dependent (“Koenig”) lookup works the way it does: if you have a class C in a namespace NS and a function void NS::f(const NS::C&), if you have NS::C c; you can call f(c); unqualified outside NS. Philosophically, C++ considers f to be a part of C’s interface.
This is currently not possible. You either have to write your own type that behaves like and int and you provide a isLife member function or you provide a free function isLife that takes an int
There was a proposal to have a universal call syntax where foo.bar() would call bar(foo) is bar is actually a free fucntion but it was rejected. Something else could come up or you could try proposing your own.
Do note that it is also illegal (per the standard) to add member functions to standard library types. You can add free functions but you are not allowed to modify the implementation.
I want to overload "->" operator globally for pointers. Is it possible?
A *var1 = new A(21);
int x = var1->someInt;
In that code it has to be triggered when reaching "var1"s "someInt" variable.
Actually I am trying to check the pointer before reaching its members. Also, I am trying to implement this system on a written code, so I don't want to change too much thing in the actual code.
I want to overload "->" operator globally. Is it possible?
No it is impossible.
Perhaps you might define a "root" class in your library or program (which would define that operator ->), and have all your classes inherit from it.
BTW, I am not sure you will be able to define your isPointerValid function in all cases (including the address of valid automatic variables of any class type), and efficiently.
There are many cases where you could not define such a function (e.g. union-s used in tagged union types; you don't easily know what member of a union is currently active. arbitrary casts; ...); .
For existing code and classes, the builtin meaning of -> (which you usually cannot redefine) has already been used to compile the code using them.
As described in C++17 standard draft in section 16.5.6 (emphasis mine):
An operator function shall either be a non-static member function or
be a non-member function that has at least one parameter whose type
is a class, a reference to a class, an enumeration, or a reference to
an enumeration.
Hence, it is not possible to overload an operator which doesn't take any arguments.
Why are those C++11 new functions of header <string> (stod, stof, stoull) not member functions of the string class ?
Isn't more C++ compliant to write mystring.stod(...) rather than stod(mystring,...)?
It is a surprise to many, but C++ is not an Object-Oriented language (unlike Java or C#).
C++ is a multi-paradigm language, and therefore tries to use the best tool for the job whenever possible. In this instance, a free-function is the right tool.
Guideline: Prefer non-member non-friend functions to member functions (from Efficient C++, Item 23)
Reason: a member function or friend function has access to the class internals whereas a non-member non-friend function does not; therefore using a non-member non-friend function increases encapsulation.
Exception: when a member function or friend function provides a significant advantage (such as performance), then it is worth considering despite the extra coupling. For example even though std::find works really well, associative containers such as std::set provide a member-function std::set::find which works in O(log N) instead of O(N).
The fundamental reason is that they don't belong there. They
don't really have anything to do with strings. Stop and think
about it. User defined types should follow the same rules as
built-in types, so every time you defined a new user type,
you'd have to add a function to std::string. This would
actually be possible in C++: if std::string had a member
function template to, without a generic implementation, you
could add a specialization for each type, and call
str.to<double>() or str.to<MyType>(). But is this really
what you want. It doesn't seem like a clean solution to me,
having everyone writing a new class having to add
a specialization to std::string. Putting these sort of things
in the string class bastardizes it, and is really the opposite
of what OO tries to achieve.
If you were to insist on pure OO, they would have to be
members of double, int, etc. (A constructor, really. This
is what Python does, for example.) C++ doesn't insist on pure
OO, and doesn't allow basic types like double and int to
have members or special constructors. So free functions are
both an acceptable solution, and the only clean solution
possible in the context of the language.
FWIW: conversions to/from textual representation is always
a delicate problem: if I do it in the target type, then I've
introduced a dependency on the various sources and sinks of text
in the target type---and these can vary in time. If I do it in
the source or sink type, I make them dependent on the the type
being converted, which is even worse. The C++ solution is to
define a protocol (in std::streambuf), where the user writes
a new free function (operator<< and operator>>) to handle
the conversions, and counts on operator overload resolution to
find the correct function. The advantage of the free function
solution is that the conversions are part of neither the data
type (which thus doesn't have to know of sources and sinks) nor
the source or sink type (which thus doesn't have to know about
user defined data types). It seems like the best solution to
me. And functions like stod are just convenience functions,
which make one particularly frequent use easier to write.
Actually they are some utility functions and they don't need to be inside the main class. Similar utility functions such as atoi, atof are defined (but for char*) inside stdlib.h and they too are standalone functions.
What are the existing rules for taking function pointers or member function pointers to Standard functions? For example, something like
auto p = &std::string::size;
Is this legal? Would it be more or less legal if I explicitly requested the correct type, so it would function even if there was an additional implementation-added overload of std::string::size?
Using the "correct" type doesn't make things better: Except for the virtual functions all functions in the standard C++ library can have additional arguments as long as these are defaulted. Since the functions can also be declared with additional overloads (again with the exception of the virtual function), you can end up trying to assign an overload set a variable. Thus, the code isn't portable and there is no way to make it portable by using some sort of cast or some signature instead of auto.
The relevant quote is 17.6.5.5 [member.functions] paragraph 1:
An implementation may declare additional non-virtual member function signatures within a class:
--- by adding arguments with default values to a member function signature;
— by replacing a member function signature with default values by two or more member function signatures with equivalent behavior; and
— by adding a member function signature for a member function name.
I don't see a similar permission for non-member functions, though. Not sure where the permission to mess with these is hiding but I'm relatively sure that there are some weasel words for these as well. Looking further, it seems non-member functions are more constrained according to 17.6.5.4 [global.functions] paragraph 3:
An implementation shall not declare a global or non-member function signature with additional default arguments.
This would imply that you can take the address of the non-member functions, at least, when specifying the desired signature.
Where in the process of creating the program, compiler, linker etc., is the overriding of functions and operator overloading done?
I'm particularly interested where it is done in C++, Ruby and Python.
Function overloading is (at least in C++) handled internally inside the compiler. The idea is that the code that the compiler ultimately generates will be hardcoded to call the appropriate function, as if the functions all had different names and you called the function uniquely suited to the arguments. More generally, in most compiled languages that support overloading, the overload resolution is done at compile-time and the emitted code will always call the indicated function. For example, Haskell supports compile-time overloading this way.
Operator overloading is a special case of general overloading, so it's usually handled the same way.
Function overriding (a term that arises in OOP when a derived class inherits from a base class and redefines one of its methods) is almost always resolved at runtime, since a compiler can't always tell which function is going to be invoked without actually knowing about the types at runtime. Some compilers might be able to statically prove that a certain object has a specific type and can then optimize the dynamic dispatch away, but it's impossible to do this in all cases.
I am not aware of any dynamic languages that support overloading, since in theory you could introduce new overload candidates as the program was running. I would love to be enlightened if such a language exists.
For C++, operator overloading is done at the compiler level though a name-mangling process that creates a unique name identifier for every function so that the linker will not complain about duplicate function definitions. In C++, operator overloading is possible because overloadable operations like +, -, *, etc. are actual functions themselves that have the prefix operator followed by the symbol of the operation. So for instance, an overloaded operator+ function with a function signature like
my_type operator+(const my_type& lhs, const my_type& rhs);
will not conflict with another operator+ function with a different signature, even though both functions have the same operator+ name, because each version of the function will have a different name at the assembly-language level after the C++ compiler's name-mangling process is complete. Name-mangling has another benefit in that allows C and C++ compiled code to be used with the same linker, since two functions with the same name will not exist and cause a linker error.
Note that in C, that even if you create two functions with different signatures, if they have the same name, since the C-compiler will not do any name-mangling, the linker will complain about duplicate definitions of the function.
Python is not linked/compiled, it is interpreted.
So, the normal overriding is done when class sources are parsed. Of course, due to dynamic nature you can always override during the runtime as well.
I suppose that alternate implementations using the byto-code compilation do it on the compile-time.
I also think the above is true for Ruby as well.