I get this error
USCENEComponent = GetComponentRotation : nonstandard syntax. Use & to create a member pointer.
when compiling this code:
if (!Player_isDead) {
FVector fwd = GetActorForwardVector();
FVector muzzle = GetMesh()->GetBoneLocation("pinky_01_r");
muzzle += fwd * 155;
AProjectile* bullet = GetWorld()->SpawnActor<AProjectile>(BPProjectile, muzzle, RootComponent->GetComponentRotation); // <<===== error
if (bullet) {
//bullet->Firer = this;
bullet->ProxSphere->AddImpulse(fwd*BulletLaunchImpulse);
}
else {
GEngine->AddOnScreenDebugMessage(0, 5.f, FColor::Yellow, "no bullet actor could be spawnd. is the bullet overlapping something?");
}
}
What should I add? I don't know offhand. Please let me know in detail. ㅠㅠ
GetComponentRotation is a method. What do you want to do with the method? Call it, or take its address? We don't know, nor does the compiler. It guesses you wanted the address. My guess would be that you wanted to call GetComponentRotation. In that case, add the argument list, even if it's empty: RootComponent->GetComponentRotation( ).
USCENEComponent = GetComponentRotation should be USCENEComponent = GetComponentRotation() (or some variant with an appropriate argument list). GetComponentRoation() is a function call; in C++ you can’t call a function without the parentheses, even if it takes no arguments.
The warning is a bit misleading. It’s really aimed at creating a pointer-to-member-function. Like this:
struct C {
void f();
};
void (C::*pmf)() = &C::f;
That bit on the right-hand-side creates a pointer to the member function f of the struct C.
The business about “non-standard syntax” is a Microsoftism. Any reasonable compiler would tell you that you need parentheses to call a function. The reason that Microsoft gives you this warning is that back in the olden days, Microsoft decided that it made sense to be able to create a pointer to member function without mentioning the class name if the context provided it for you and, while you were being lazy, without the &. So this was legal with Microsoft’s compiler:
struct C {
void f();
void g() { void (C::*pmf)() = f; }
};
They even floated a paper at one of the standards meetings suggesting that the standard should allow this syntax. That didn’t go anywhere.
So, having (erroneously) allowed that syntax, they opted for backward compatibility by giving a misleading warning for code that uses their invalid syntax. Formally, that’s okay: the only requirement that the standard imposes for non-conforming code is that the compiler “issue a diagnostic”, and every compiler I know of considers a warning to be a diagnostic.
Related
So I have a function with a specific signature in a header file, and I want to declare another function with the exact same signature inside a class without typing the parameters again, and of course, hopefully without a macro... The member function should also have an extra hidden parameter obviously, the this pointer (since it's not a static member function).
Now, I'm actually surprised that the following hack/trick works in both GCC and ICC, but I'm not sure if it's "legal" C++. I'm not particularly concerned with legality if it's a supported extension, but unfortunately I do not want it to break on a compiler version update because some people decided to arbitrarily block this useful feature since the standard says "no" (that kind of stuff really annoys me to be honest).
Here's what I mean:
// test.hpp
int func(int x) { return x; }
struct foo
{
decltype(func) fn; // <-- legal?
};
int test()
{
return foo().fn(6);
}
// then in test.cpp
int foo::fn(int x) { return x + 42; }
This works (with GCC and ICC), but I don't know if it's "legal" in the standard. I'm asking just to be assured that it is legal and it won't suddenly stop working in the future.
(if it's not legal and you want to report it as a bug, please mark it as a suggestion to make it a legal compiler extension instead of killing it...)
Basically, it's the same as declaring int fn(int x); in the struct, and that's how it works currently.
If you ask me for a use case: it's to declare a wrapper member function for the other free function which does something with the this pointer before passing it to the free function. Its parameters must match exactly, obviously. Again, I don't want to type the parameters again.
That looks legal; but at definition you have to retype. Consider using perfect forwarding instead.
Caution: This problem is limited to MSVS
I have this function signature:
void do_somthing(std::vector<foo>& bar={});
Is it possible to differ between those two calls for the function:
First:
do_something()
Second:
std::vector<foo> v;
do_something(v);
In other words, I want something like:
void do_somthing(std::vector<foo>& bar={}){
if(/* bar was defaulted*/){
}
else{
}
}
EDIT:
The actual code:
template<class Tinput_iterator>
Tmodel perform_fitting(Tinput_iterator begin_data, Tinput_iterator end_data, std::vector<Tpoint>& inliers = {});
No, not directly. The default parameter is substituted by the compiler at the call site without any further information.
However, there is a simple solution to achieve what you want to do: Use overloading instead of default parameters.
namespace detail
{
void
do_something_impl(const std::vector<foo>& foos)
{
// Do things that always need to be done…
}
}
void
do_something()
{
// Do things specific to the no-argument case…
detail::do_something_impl({});
}
void
do_something(const std::vector<foo>& foos)
{
// Do things specific to the one-argument case…
detail::do_something_impl(foos);
}
If your logic requires you to branch more often – not just at the beginning or the end of the function – you could pass an additional boolean parameter to detail::do_something_impl that encodes which overload it was called from.
In general, I recommend to use defaulted parameters sparingly and prefer function overloading as it gives you better control and often also better (less surprising) interfaces.
I have this function signature:
void do_somthing(std::vector<foo>& bar=std::vector<foo>{});
This cannot compile, except with dangerous non-standard compiler settings you should stay away from.
In particular, Visual C++ allows this if /Za is not specified, but with /W4 still produces a warning like this:
stackoverflow.cpp(6): warning C4239: nonstandard extension used: 'default argument': conversion from 'std::vector<foo,std::allocator<_Ty>>' to 'std::vector<foo,
std::allocator<_Ty>> &'
with
[
_Ty=foo
]
stackoverflow.cpp(6): note: A non-const reference may only be bound to an lvalue
void do_somthing(std::vector<foo>& bar=std::vector<foo>{}){
if(/* bar was defaulted*/){
}
else{
}
}
Even if we assume that you actually included the missing const to make the code compile, the answer would be: no, it is not possible to know if bar was defaulted.
Whatever you plan to do here, you have to find a completely different solution.
Is it possible to differ between those two calls for the function?
No. You can check if the vector is empty, but otherwise there is no way to distinguish them.
You can do clever things, such as passing a utility class that converts, but that isn't bulletproof and is mostly pointless since you can more easily make two different function overloads.
I'm trying to compile an old code that uses pointers to (non-static) member functions, but it won't compile because the syntax is different now. I can only create a pointer to a function Foo by typing &Bar::Foo, which didn't use to be the case (simply typing Foo would create a member pointer).
When was this syntax added and is there a way to allow the old syntax in VisualStudio to avoid modifying the old code?
Here's a random example, which used to compile:
class Foo
{
public:
int Bar(int x)
{
return x + 2;
}
Foo();
};
int (Foo::*f)(int);
Foo::Foo()
{
f = Bar; // error, have to use f = &Foo::Bar now
}
You don't specify in your question, but whenever I hear the words "the syntax is different," I assume you are migrating from Visual C++ 6 to a newer version of Visual Studio.
The long and short of it is; Visual C++ 6 does not use "standards-compliant C++." Migrating from Visual C++ 6 to any other modern compiler will cause many syntax errors, and will take some effort to migrate into "compliance." You'll just have to suck it up and make the syntax changes.
Off-hand; I don't have a source to back me up, but I would be willing to bet that your function pointer syntax falls into this category.
The good news is; once you've done it, pretty much all the rest of the modern compilers in the world will work with standards-compliant code, so you should only ever have to do this once.
Update:
I did a quick search and found at least one source which seems to confirm the MSVC6 behavior:
"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."
Following may help:
class A
{
public:
void foo();
};
int main(int argc, char* argv[])
{
void (A::*mem_func)() = &A::foo;
A a;
(a.*mem_func)();
return 0;
}
No, you have to use the standards compliant syntax for the type of, for creating and for calling member function pointers. VC++6 was more generous; e.g. when you wanted to create a function pointer you don't need to name the class it's in, unless ambiguous; that's simply not possible in standard C++.
The type of member function pointer to a function like
int Bar::Foo(int x);
is
int (Bar::*)(int)
and with a name (e.g. a variable or parameter of this type):
int (Bar::*function)(int)
To create a member function pointer you have to use the ampersand operator:
function = &Bar::Foo;
To call such a function you need the following syntax (assuming bar is a Bar*):
(bar->*function)(42);
or (if bar is a Bar):
(bar.*function)(42);
or (if bar is a smart pointer to Bar implementing operator*):
((*bar).*function)(42);
I've recently spent a lot of time with javascript and am now coming back to C++. When I'm accessing a class member from a method I feed inclined to prefix it with this->.
class Foo {
int _bar;
public:
/* ... */
void setBar(int bar) {
this->_bar = bar;
// as opposed to
_bar = bar;
}
}
On reading, it saves me a brain cycle when trying to figure out where it's coming from.
Are there any reasons I shouldn't do this?
Using this-> for class variables is perfectly acceptable.
However, don't start identifiers with an underscore, or include any identifiers with double underscore __ anywhere. There are some classes of reserved symbols that are easy to hit if you violate either of these two rules of thumb. (In particular, _IdentifierStartingWithACapital is reserved by the standard for compilers).
In principle, accessing members via this-> is a coding style that can help in making things clearer, but it seems to be a matter of taste.
However, you also seem to use prefixing members with _ (underscore). I would say that is too much, you should go for either of the two styles.
Are there any reasons I shouldn't do this?
Yes, there is a reason why you shouldn't do this.
Referencing a member variable with this-> is strictly required only when a name has been hidden, such as with:
class Foo
{
public:
void bang(int val);
int val;
};
void Foo::bang(int val)
{
val = val;
}
int main()
{
Foo foo;
foo.val = 42;
foo.bang(84);
cout << foo.val;
}
The output of this program is 42, not 84, because in bang the member variable has been hidden, and val = val results in a no-op. In this case, this-> is required:
void Foo::bang(int val)
{
this->val = val;
}
In other cases, using this-> has no effect, so it is not needed.
That, in itself, is not a reason not to use this->. The maintennance of such a program is however a reason not to use this->.
You are using this-> as a means of documentation to specify that the vairable that follows is a member variable. However, to most programmers, that's not what usign this-> actually documents. What using this-> documents is:
There is a name that's been hidden here, so I'm using a special
technique to work around that.
Since that's not what you wanted to convey, your documentation is broken.
Instead of using this-> to document that a name is a member variable, use a rational naming scheme consistently where member variables and method parameters can never be the same.
Edit Consider another illustration of the same idea.
Suppose in my codebase, you found this:
int main()
{
int(*fn)(int) = pingpong;
(fn)(42);
}
Quite an unusual construct, but being a skilled C++ programmer, you see what's happening here. fn is a pointer-to-function, and being assigned the value of pingpong, whatever that is. And then the function pointed to by pingpong is being called with the singe int value 42. So, wondering why in the world you need such a gizmo, you go looking for pingpong and find this:
static int(*pingpong)(int) = bangbang;
Ok, so what's bangbang?
int bangbang(int val)
{
cout << val;
return val+1;
}
"Now, wait a sec. What in the world is going on here? Why do we need to create a pointer-to-function and then call through that? Why not just call the function? Isn't this the same?"
int main()
{
bangbang(42);
}
Yes, it is the same. The observable effects are the same.
Wondering if that's really all there is too it, you see:
/* IMPLEMENTATION NOTE
*
* I use pointers-to-function to call free functions
* to document the difference between free functions
* and member functions.
*/
So the only reason we're using the pointer-to-function is to show that the function being called is a free function
and not a member function.
Does that seem like just a "matter of style" to you? Because it seems like insanity to me.
Here you will find:
Unless a class member name is hidden, using the class member name is equivalent to using the class member name with the this pointer and the class member access operator (->).
I think you do this backwards. You want the code to assure you that what happens is exactly what is expected.
Why add extra code to point out that nothing special is happening? Accessing class members in the member functions happen all the time. That's what would be expected. It would be much better to add extra info when it is not the normal things that happen.
In code like this
class Foo
{
public:
void setBar(int NewBar)
{ Bar = NewBar; }
you ask yourself - "Where could the Bar come from?".
As this is a setter in a class, what would it set if not a class member variable?! If it wasn't, then there would be a reason to add a lot of info about what's actually going on here!
Since you are already using a convention to signify that an identifer is a data member (although not one I would recommend), adding this-> is simply redundant in almost all cases.
This is a somewhat subjective question obvously. this-> seems much more python-idiomatic than C++-idiomatic. There are only a handful of cases in C++ where the leading this-> is required, dealing with names in parent template classes. In general if your code is well organized it will be obvious to the reader that it's a member or local variable (globals should just be avoided), and reducing the amount to be read may reduce complexity. Additionally you can use an optional style (I like trailing _) to indicate member variables.
It doesn't actually harm anything, but programmers experienced with OO will see it and find it odd. It's similarly surprising to see "yoda conditionals," ie if (0 == x).
I recently had an exchange with another C++ developer about the following use of const:
void Foo(const int bar);
He felt that using const in this way was good practice.
I argued that it does nothing for the caller of the function (since a copy of the argument was going to be passed, there is no additional guarantee of safety with regard to overwrite). In addition, doing this prevents the implementer of Foo from modifying their private copy of the argument. So, it both mandates and advertises an implementation detail.
Not the end of the world, but certainly not something to be recommended as good practice.
I'm curious as to what others think on this issue.
Edit:
OK, I didn't realize that const-ness of the arguments didn't factor into the signature of the function. So, it is possible to mark the arguments as const in the implementation (.cpp), and not in the header (.h) - and the compiler is fine with that. That being the case, I guess the policy should be the same for making local variables const.
One could make the argument that having different looking signatures in the header and source file would confuse others (as it would have confused me). While I try to follow the Principle of Least Astonishment with whatever I write, I guess it's reasonable to expect developers to recognize this as legal and useful.
Remember the if(NULL == p) pattern ?
There are a lot of people who will tell a "you must write code like this":
if(NULL == myPointer) { /* etc. */ }
instead of
if(myPointer == NULL) { /* etc. */ }
The rationale is that the first version will protect the coder from code typos like replacing "==" with "=" (because it is forbidden to assign a value to a constant value).
The following can then be considered an extension of this limited if(NULL == p) pattern:
Why const-ing params can be useful for the coder
No matter the type, "const" is a qualifier that I add to say to the compiler that "I don't expect the value to change, so send me a compiler error message should I lie".
For example, this kind of code will show when the compiler can help me:
void bar_const(const int & param) ;
void bar_non_const(int & param) ;
void foo(const int param)
{
const int value = getValue() ;
if(param == 25) { /* Etc. */ } // Ok
if(value == 25) { /* Etc. */ } // Ok
if(param = 25) { /* Etc. */ } // COMPILE ERROR
if(value = 25) { /* Etc. */ } // COMPILE ERROR
bar_const(param) ; // Ok
bar_const(value) ; // Ok
bar_non_const(param) ; // COMPILE ERROR
bar_non_const(value) ; // COMPILE ERROR
// Here, I expect to continue to use "param" and "value" with
// their original values, so having some random code or error
// change it would be a runtime error...
}
In those cases, which can happen either by code typo or some mistake in function call, will be caught by the compiler, which is a good thing.
Why it is not important for the user
It happens that:
void foo(const int param) ;
and:
void foo(int param) ;
have the same signature.
This is a good thing, because, if the function implementer decides a parameter is considered const inside the function, the user should not, and does not need to know it.
This explains why my functions declarations to the users omit the const:
void bar(int param, const char * p) ;
to keep the declaration as clear as possible, while my function definition adds it as much as possible:
void bar(const int param, const char * const p)
{
// etc.
}
to make my code as robust as possible.
Why in the real world, it could break
I was bitten by my pattern, though.
On some broken compiler that will remain anonymous (whose name starts with "Sol" and ends with "aris CC"), the two signatures above can be considered as different (depending on context), and thus, the runtime link will perhaps fail.
As the project was compiled on a Unix platforms too (Linux and Solaris), on those platforms, undefined symbols were left to be resolved at execution, which provoked a runtime error in the middle of the execution of the process.
So, because I had to support the said compiler, I ended polluting even my headers with consted prototypes.
But I still nevertheless consider this pattern of adding const in the function definition a good one.
Note: Sun Microsystems even had the balls to hide their broken mangling with an "it is evil pattern anyway so you should not use it" declaration. see http://docs.oracle.com/cd/E19059-01/stud.9/817-6698/Ch1.Intro.html#71468
One last note
It must be noted that Bjarne Stroustrup seems to be have been opposed to considering void foo(int) the same prototype as void foo(const int):
Not every feature accepted is in my opinion an improvement, though. For example, [...] the rule that void f(T) and void f(const T) denote the same function (proposed by Tom
Plum for C compatibility reasons) [have] the dubious distinction of having been voted into C++ “over my dead body”.
Source: Bjarne Stroustrup
Evolving a language in and for the real world: C++ 1991-2006, 5. Language Features: 1991-1998, p21.
http://www.stroustrup.com/hopl-almost-final.pdf
This is amusing to consider Herb Sutter offers the opposite viewpoint:
Guideline: Avoid const pass-by-value parameters in function declarations. Still make the parameter const in the same function's definition if it won't be modified.
Source: Herb Sutter
Exceptional C++, Item 43: Const-Correctness, p177-178.
This has been discussed many times, and mostly people end up having to agree to disagree. Personally, I agree that it's pointless, and the standard implicitly agrees -- a top-level const (or volatile) qualifier doesn't form part of the function's signature. In my opinion, wanting to use a top-level qualifier like this indicates (strongly) that the person may pay lip-service to separating interface from implementation, but doesn't really understand the distinction.
One other minor detail: it does apply to references just as well as pointers though...
It makes the compiler do part of the work of catching your bugs. If you shouldn't be modifying it, make it const, and if you forget, the compiler will yell at you.
If bar is marked const as above, then the person reading the code, knowing what was passed in, knows at all time exactly what bar contains. There's no need to look at any code beforehand to see if bar got changed at any point along the way. This makes reasoning about the code simpler and thus reduces the opportunity for bugs to creep in.
I vote "good practice" myself. Of course I'm also pretty much a convert to functional languages these days so....
Addressing the comment below, consider this source file:
// test.c++
bool testSomething()
{
return true;
}
int test1(int a)
{
if (testSomething())
{
a += 5;
}
return a;
}
int test2(const int a)
{
if (testSomething())
{
a += 5;
}
return a;
}
In test1 there is no way for me to know what the value being returned will be without reading the (potentially sizable and/or convoluted) body of the function and without tracking down the (potentially distant, sizable, convoluted and/or source-unavailable) body of the function testSomething. Further, the alteration of a may be the result of a horrific typo.
That same typo in test2 results in this at compile-time:
$ g++ test.c++
test.c++: In function ‘int test2(int)’:
test.c++:21: error: assignment of read-only parameter ‘a’
If it was a typo, it's been caught for me. If it isn't a typo, the following is a better choice of coding, IMO:
int test2(const int a)
{
int b = a;
if (testSomething())
{
b += 5;
}
return b;
}
Even a half-baked optimizer will generate identical code as in the test1 case, but you're signalling that care and attention will have to be paid.
Writing code for readability involves a whole lot more than just picking snazzy names.
I tend to be a bit of a const fiend so I personally like it. Mostly it's useful to point out to the reader of the code that the variable passed in wont be modified; in the same way that I try to mark every other variable that I create within a function body as const if it's not modified.
I also tend to keep the function signatures matching even though there's not much point in it. Partly it's because it doesn't do any harm and partly it's because Doxygen used to get a bit confused if the signatures were different.