This question already has answers here:
Method chaining in C++?
(2 answers)
Closed last month.
for example in C++ we use:
int a = 12;
typeid(a).name();
to get type of a variable
my question is what exactly typeid is (im nearly sure its a function but Clion shows nothing)
and if its a function how it inherites or something the name() function
i tried to get what type id is but Clion showed nothing (when suggestion pops up in Clion for example when u type na it shows the suggestion and it shows and f infront of name so i know its a function but for typeid its empty)
edit:
is there a way to make something similar?
nearly all 3 answers were really good i appreciate all of them
According to cppreference, typeid
refers to a std::type_info object representing the type type. If type is a reference type, the result refers to a std::type_info object representing the cv-unqualified version (since C++11) of the referenced type.
So typeid(x) returns a std::type_info object that has methods you can query:
https://en.cppreference.com/w/cpp/types/type_info
typeid is a bit special since it's a keyword, which is likely why you weren't able to find too much information regarding it on CLion. Similarly you won't be able to find much on other keywords like int or if.
Nonetheless, the result of using typeid(some_variable) would be an std::type_info(a perfectly fine class), which would allow you to continue calling member functions like .name().
The construct does the following: the first function call has a return value of an object, which has the second function name as a member function.
E.g. in a more generic context:
#include <iostream>
struct AnObject {
void anotherFunctionName() {
std::cout << "anotherFunctionName() member of AnObject was called" << std::endl;
}
};
AnObject aFunctionName() {
std::cout << "aFunctionName() was called, returning AnObject" << std::endl;
return AnObject();
}
int main() {
// Return an instance of AnObject, and call its member function:
aFunctionName().anotherFunctionName();
}
This will output:
aFunctionName() was called, returning AnObject
anotherFunctionName() member of AnObject was called
Related
I saw this question recently Is returning by rvalue reference more efficient? and also noticed the comments chain. I am following up on the comments chain for the answer there.
People seem to say that in the case below the return value should be by rvalue reference and not by value. (Is returning by rvalue reference more efficient? and Is there any case where a return of a RValue Reference (&&) is useful?) Given the following code
#include <iostream>
using namespace std;
class Something {
public:
Something() {
cout << "Something()" << endl;
}
Something(const Something&) {
cout << "Something(const Something&)" << endl;
}
Something(Something&&) {
cout << "Something(Something&&)" << endl;
}
};
class Maker {
public:
Something get_something() && {
return std::move(this->something);
}
const Something& get_something() & {
return this->something;
}
private:
Something something;
};
int main() {
auto maker = Maker{};
auto something_one = maker.get_something();
auto something_two = Maker{}.get_something();
return 0;
}
What is the difference between defining the first method in the class Maker with an rvalue reference return type and a regular value? Running the code above gives me the following output as expected (the move happens in the function call and after the return the move is elided)
Something()
Something(const Something&)
Something()
Something(Something&&)
And when I change the code (i.e. the first method in the Maker class) to return an rvalue reference I still get the same output. Why shouldn't I just return by value in that case?
When you use this reference qualifiers in this way, you have to ask yourself two questions:
What does std::move(object).funcname() mean?
What does Typename().funcname() mean?
If you return a value from the function, then both of those will mean the same thing. Regardless of what you do to capture the value, the value will be a whole and distinct object, move-constructed from some internal data stored in the object.
In the first case, object now potentially no longer owns the data. In the second case, it doesn't matter because the object was a temporary and has since been destroyed.
If you return a && from the function, then those will mean different things. Namely, #2 will mean "your code is broken".
As to why you might still want to do it, even if it allows broken code. Well, that has to do with the actual answers to that question: what do those things mean?
Here's what I am referring to. std::get is basically a member function of tuple. And yet, if you pass it a tuple&&, you will get a T&& returned and not a T. Why?
Because you're accessing a member of the tuple.
If you had a struct, then std::move(struct_object).x would be an rvalue reference as well. So std::get is simply behaving in the same way for a tuple as member access would for a struct. That's kinda the whole point of tuple, after all: to behave like a struct as much as possible.
This allows you to do things like std::get<0>(std::move(tpl)).member, such that member will still be an rvalue reference. So you can move from a subobject without disturbing the rest of the object, exactly as you could for any other rvalue reference member accesses.
If get returned a value, then this would do something very different. Regardless of what we do with the return value, it will be moved out of the object, no questions asked. So if we only wanted to move a subobject of that member... too bad. The original object lost the entire member, not just a subobject of that member.
Of course, that doesn't change the fact that:
auto &&x = SomeStruct().x; //This extends the temporary's lifetime
auto &&x = std::get<0>(SomeTuple(...)); //This gets a dangling reference.
That is an unfortunate limitation of the language. But if the function is logically a member accessor, then returning a && from a && qualified this function instead of a value is a legitimate choice.
It all depends on what matters more to you: safety or orthogonality with member accessors.
I have currently defined a function pointer and to me it seems like the function matches the definition, however I am getting an error:
1 IntelliSense: a value of type "std::string (RSSCrawler::)(const web::json::value &headlines)" cannot be assigned to an entity of type "std::string ()(const web::json::value &headlines)"
I am not sure what is wrong, but here is my code
string(*GetHeadline)(const value&headlines);
GetHeadline = Extract;
string RSSCrawler::Extract(const value &headlines)
{
return "";
}
The compiler explained this with a type mismatch error and showing the difference in the first set of parentheses. You need a member function pointer. That is a separate type from a 'plain'/free function pointer. (static member functions act like free functions in this sense, but that's not what you have.)
You can find plenty tutorials about these, but here's a quick reference. (I have to restrain myself not to de-capitalise these function and variable names because it just looks wrong, even without SO's auto-formatting.)
// Declare pointer-to-member-function of a given class and signature
std::string (RssCrawler::* GetHeadline)(const value&);
// Bind it to any method of the same class and signature
GetHeadline = &RssCrawler::Extract;
// Call it on a given instance of said class
std::cout << (someInstance.*GetHeadline)(someValue) << std::endl; // operator .*
Or you can do this to get a const initialised pointer, though I think that defeats the purpose of a function pointer, except for const-correctness when declaring them as arguments to other functions...
std::string (RssCrawler::*const GetHeadline)(const value&) {
&RssCrawler::Extract
}
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
casting unused return values to void
What is the purpose of (void) before a function call, for example
(void)func1();
I assume this is the same as simply calling func1();
Therefore is the (void) call simply to let other programmers know that the return type will be ignored, for instance if func1() had a return type of int, or does the compiler perhaps perform some optimizations on the function? Perhaps there is another reason behind it altogether - is it even legal C++ or perhaps is it a remnant of C seen in some legacy code.
Thanks
A cast to void can have semantic effect in one case: where a value is an operand of the comma operator and overrides the comma operator, a cast to void will suppress it:
struct S {
int operator,(int) { return 0; }
};
std::cout << (S(), 42) << '\n'; // prints '0'
std::cout << ((void) S(), 42) << '\n'; // prints '42'
It prevents warning if some function are declared with attribute : "Warn if return value not used/checked"
Maybe a duplicate of Warning: ignoring return value of 'scanf', declared with attribute warn_unused_result
Check the documentation of gcc : http://gcc.gnu.org/onlinedocs/gcc/Function-Attributes.html (warn_unused_result) for more details
It means very little. It is explicitly turning the line to a void expression, that is an expression that is only used for its side effects and whose value is discarded. So the lines
func1();
and
(void)func1();
will do the same thing. There could be some optimization that can be performed if the compiler knows the value of the expression is not used, but it is likely that compiler can figure it out with or without the explicit (void).
It could be used as a form of documentation where the programmer is trying to make it obvious that they are not using the value of the expression.
Another strange use is to allow the function of unknown return type to be used adjacent to the , operator as a sequence operator. Ie, decltype( f(), g() ) technique, where you want to say "f can be operated on with (), as can g, and I want this type to be the type that g() returns". However, if f() returns a type such that operator, is overloaded, the result will be unexpected.
So you do decltype( void(f()), g() ), and discard the return value of f() before invoking operator,, so you are guaranteed to get the built-in sequence operator instead of some unknown override type.
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
C++ functions: ampersand vs asterisk
What are the distinctions between the various symbols (*,&, etc) combined with parameters?
I am wondering the difference between the address operator & and the deference operator * in a C++ function call. For example take the following function
void foo (std::string& param)
{
param = "Bar.";
std::cout << param.size();
}
and let's call it in our main() function like so...
int main()
{
std::string test;
foo(test); //Why not foo(&test)?
std::cout << test; //Prints out the value "Bar."
}
First off, why does the & operator allow me to assign a value as if it were a pointer (assigning it a value that survives the RAII and scope of the function foo() when it's not a pointer) as it is able to be printed out in my main() function even though it's not static? I am assuming it is not a pointer because I am able to access the size() method by using the . operator instead of the -> which is used for pointers.
Secondly, what would be the difference between using the & operator in a function parameter vs. using the * operator? Is it even different than just a plain variable like std::string param? It appears to be called like that (foo(test) instead of foo(&test)).
& function parameter specifically signifies that this parameter is being passed-in by reference (traditionally compilers implement this as a pointer) which is why you see the effect of this assignment in your main().
static would have nothing to do with that.
The difference in declaring a parameter to a function using & and * is that the second one allows a nullptr (or a non-existent or just a plain invalid address) to be passed-in while the & guarantees that there's a real object being referenced by this function's argument. Other than that both provide similar functionality of allowing an original object to be changed via it's reference.
test on it's own (without &) would pass a copy to the string to the function, whilst the & means it will pass a reference.
FYI: When you don't need a reference, best-practise dictates passing all objects as const references.
While trying to answer this question I found without () (which invokes "C++ most vexing parse") the output of g++ is 1 (Can be seen here: http://ideone.com/GPBHy), where as visual studio gives a linker error. I couldn't understand how the output can 1, any clues?
As the answers to the question already explain, due to the "Most Vexing Parse" the statement instead of defining an object named str with the two istream_iterators to specify its initializers, is parsed as a declaration of a function named str that returns a string.
So a simple version of the program resolves to, this online sample:
#include<iostream>
void doSomething()
{
}
void (*ptr)()=&doSomething;
int main()
{
std::cout << ptr << "\n";
std::cout << doSomething;
return 0;
}
Output:
1
1
Note that there is no overloaded operator << that takes an std::ostream and a function pointer as arguments, this is because there can be any number of user defined function types and ofcourse a standard overloaded api cannot account for them all.
Given that the compiler tries to find the best match among the existing overloads which happens to be bool (a function pointer is implicitly convertible to bool[#1]).
In particular,
basic_ostream& operator<< (bool& val );
Since the function pointer points to something and not null, the value is printed as 1.
[#1]C++03 4.12 Boolean conversions
1 An rvalue of arithmetic, enumeration, pointer, or pointer to member type can be converted to an rvalue of type bool.