C++/ name conflict: how to exclude a previously defined function - c++

I want to write log2() function for a new datatype that I defined myself Array. So it will look like this
#include <iostream>
#include <cmath>
Array log2(Array& A)
{
Array C=A;
for (int i=0; i<A.size(); i++)
C[i]=log2(A[i]);
return C;
}
despite other functions like sin, cos, etc, this one (log2) is not declared under std namespace. so even using the following
std::log2(A[i])
the compiler does not resolve that inside log2 is suppoed to be the built-in c function. I persist to use the same name (log2) for simplicity of the code.
This is the error message
error: invalid initialization of reference of type 'Array&' from expression of type 'double'
SOLVED: It worked when I switched to -std::C++ 11.

std::log2 was introduced in C++11. Make sure you have a C++11 compliant compiler (e.g. gcc4.8 or later, compile with -std=c++11), and use std::log2 inside your function.
If you don't use std::log2, then the compiler cannot find the standard function (as you are not using namespace std;) and tries to use yours, which of course is not defined for doubles, and you get an error.
My personal opinion is that you should try to avoid naming your function the same as a standard one, due to headaches that can later appear.

As far as I know, the built-in function log2 is not declared in namespace std.
You should use the following code to call the standard log2 function:
log2(A[i]);
I hope my answer helped.

Related

Is writing "std::" before stoi(s.substr(2,3)) mandatory?

I have seen that even if you don't add std:: before stoi(s.substr(3,4)) (where s="123456789") it works fine, and also if you write std::stoi(s.substr(3,4)) the result is the same. So, is writing it like std::stoi(s.substr(3,4)) mandatory, or is it just good practice?
std::string s = "123456789";
int ans = stoi(s.substr(3,4));
std::cout<<ans;
std::string s = "123456789";
int ans = std::stoi(s.substr(3,4));
std::cout<<ans;
Both gives the same answer. And also sometimes writing std::stoi(s.substr(3,4)); gives an error.
It compiles without std:: because of the argument-dependent lookup.
I say it's a good practice to use std::stoi because:
It's more obvious that a standard function is being called.
It will not break if someone defines a variable named stoi prior to your code. This can be fixed by adding using std::stoi;, but since you call it once, it's more verbose than calling std::stoi directly.
It is considered good practice to add std:: namespace, so you can avoid conflicts if you use different libraries etc.
The probable reason it gives you an error sometimes is because you probably don't include the string header of the standard library:
#include <string>
but it is difficult without seeing the error, so please provide the details
Likely, if you can use stoi and get the same result as std::stoi, you might be using namespace std already.
This is not always desirable, depending on the project philosophy and the rest of your code suggests that you shouldn't depend on it.
edit: in this case, OP does not use using namespace std and something more subtle is going on (thanks #HolyBlackCat).
stoi() exists in the std namespace, so using stoi() without std:: works if there is a preceding using namespace std; or using std::stoi; statement, or when passing in a std::string object as an argument value due to Argument-Dependent Lookup (since string and stoi() are in the same namespace).

Passing pointer as argument c++ 2 compilers different results

I was working with another computer science student today, and he said his class was covering pointers. He was trying to understand pointers by creating an example where he was passing a pointer as an argument to a function, and setting that referenced pointer argument inside the function equal to the hypotenuse of a triangle (two of the other sides of the triangle are also passed into the function as double arguments).
As I explained to him about how pointers worked, I coached him what he should do, and we ended up with something like the example code I have below. His compiler continually failed to compile despite our efforts, but the compiler for VS2013 worked okay.
My question is simply this: Is there anything we're doing wrong with the code I've presented below? I did tell him that you'd probably use dynamic memory allocation instead of setting the pointer equal to the address of another variable we define in the program, but it seems baffling to me why the code won't compile. Same exact code, one compiles, the other doesn't. I just want to be sure the information I'm giving out is correct, of course.
And of course, much thanks to the stackoverflow community.
#include <iostream>
#include <cmath>
using namespace std;
void hypotenuse(double a, double b, double *ptr);
int main()
{
//double *ptr = new double;
double *ptr;
double c;
ptr = &c;
hypotenuse(3, 4, ptr);
cout << ptr << '\n' << *ptr;
cin.get();
}
void hypotenuse(double a, double b, double *ptr)
{
*ptr = sqrt(a*a + b*b);
}
Post was edited because we did include the cmath header, I just forgot to write it in this example because VS2013 doesn't require it. My apologies.
Both GCC and Visual C++ are conforming here. If we look to the draft C++ standard, section [res.on.headers]:
A C++ header may include other C++ headers. A C++ header shall provide
the declarations and definitions that appear in its synopsis. A C++
header shown in its synopsis as including other C++ headers shall
provide the declarations and definitions that appear in the synopses
of those other headers.
Somewhere in its standard library, Visual C++ decided to include <cmath>. From now on, follow good practice and always include headers for functions you use.
The code as posted in this question will not compile with gcc as is because it is lacking the include of the math header that defines sqrt. Your compiler error/warnings should clearly show this problem, pay close attention to those messages.
Because sqrt is not part of the c++ language you have to add an include for the cmath header. It is possible that in some iteration of your friends code you had included this header directly or indirectly however without the information about the compiler used there and an exact error message this is purely speculation, you need to include that information in a question like this to get a better answer. When you include the cmath the code will compile and run without issue.
What is the wanted result of your code?
You are calculating a hypotenuse and then
Displaying pointer's address ptr and double c's contents.
Prossible mistakes:
Omitted header for the calculations inside the function
Solution:
add header the line: #include <cmath>
I'm pretty close to closing this question. I don't think I will be able to get the compiler error message, and the question that was really being asked here was if I did anything wrong in the code that I shouldn't do. It seems to me that the answer to the question is, "Well, that depends," and it depends on the compiler; but I would like to write code that is, of course, portable.
Now, I know I've made a few small errors of bad programming practice, such as not passing by reference, forgetting to include the header for cmath, and maybe assigning a pointer to the address of an undefined variable.... and I could have made a return type instead of passing a pointer argument and so on. Although, it doesn't seem that I've done anything that should invoke the compiler error, but hey, who am I and what do I know?
I cannot get the error message from the student who compiled the code, but I believe the IDE he was using was cloud nine, an online IDE that works in browser. I don't know which version of gcc or g++ it's using, and I went to the website, signed up, and was able to compile my code just fine. I can assure you it was the same exact code I used because I took it from my email, the same code he was unable to compile on his own machine or on his own account at cloud 9.
So I think the answer to this question is that I haven't done anything that would violate the language of C++, if I can put it that way.
Anyway, just thought I'd say thanks anyway, and sorry for wasting people's time.
First off initializing a pointer without a value (double* ptr;) is bad practice and could lead to undefined behavior.
Most of the time you should not declare a void _ (T,T*) function and should instead replace the T* with a return value. This allows for return value optimizations to basically inline the functional call. It also is much more readable:
double hyp;
hypotenuse(3, 4, &hyp);
vs
double hyp = hypotnuse(3, 4);
I understand that you were teaching about pointers, but still it is much better to do an example where pointers/references make sense:
int /* error code */
getyx(int* y, int* x);
Then you can use:
int y,x;
if(getyx(&y,&x)) {
/* use value */
} else {
/* error handling */
}

c++11 tie name clash with boost

I am trying to migrate some code from boost::tuple to std::tuple but I'm getting some weird errors: after I invoke using namespace std (and never boost), I expect an unqualified tie to resolve to std::tie. However, this seems to fail when the tuple contains a boost container pointer, for example.
#include <tuple>
#include <boost/multi_index_container.hpp>
#include <boost/multi_index/ordered_index.hpp>
#include <boost/multi_index/identity.hpp>
#ifdef USE_STD
#define TIE std::tie
#else
#define TIE tie
#endif
typedef boost::multi_index_container<
int,
boost::multi_index::indexed_by<
boost::multi_index::ordered_non_unique<
boost::multi_index::identity<int>
>
>
> Set;
std::tuple< int, int* > make_i_ptr();
std::tuple< int, Set* > make_set();
int main()
{
using namespace std;
int i;
int* i_ptr;
Set* set_ptr;
tie(i, i_ptr) = make_i_ptr();
TIE(i, set_ptr) = make_set();
return 0;
}
If I compile with g++ -std=c++0x -c test.cpp -DUSE_STD, all is well. However, without -D USE_STD, I get compile errors suggesting g++ tries to use boost::tuples::tie. I'm using g++ 4.8.1 and boost 1.55.0. Do you think this is a bug with boost? Or is there some spec I'm missing?
Lookup is complicated. The problem as others have mentioned is Argument Dependent Lookup or ADL. The rules for ADL were added to allow the definition of operators in the same namespace as the types they refer to, and enabling lookup to find those operators when present. This was later extended to all other functions in the process of standarization.
The issue here is that tie(...) is a function call. The compiler will attempt regular lookup from the point of use (inside main) it will move out to the enclosing namespace. The using directive will add ::std into the lookup search when it hits the root namespace (common ancestor of ::std and ::main). At that point, since the identifier resolves to a function, ADL will kick in.
ADL adds the namespaces associated to the arguments of the function call, which in this case is boost:: (fundamental types like int have no associated namespaces). At this point the compiler sees two declarations of tie: std::tie and boost::tie, causing ambiguity.
As you already know the solution is to qualify the call to std::tie (which I would advice that you use even without this issue). Regarding the comment:
If ADL makes it resolve to boost::tie for... "my convenience" and then the compilation fails, shouldn't that be a clue to the compiler that it picked the wrong function?!
I don't know what the exact error you are getting is (I don't use boost, and I don't know what possible overloads of std::tie it contains). If the problem is indeed one of ambiguity, the problem is that the compiler cannot resolve the identifier, and cannot continue the process. At that point it stops and asks for the programmer to resolve it. If the error is that it uniquely picked boost::tie and it later failed in the assignment, it means that theres is an overload of boost::tie that is a better match than std::tie and that was selected. At a later time the assignment from std::tuple may have failed, but the compiler cannot know whether the problem was during lookup, or whether it is the assignment itself (did you intend on assigning that variable? maybe a different one?) so again it fails and tells you what the problem is.
Note that in general the process of compilation is always moving forward, the compiler does not backtrack to double guess its own decisions*. There is a set of rules, and those rules are applied at each step. If there is ambiguity, compilation stops, if not, then there is a single best candidate and this point is resolved, moving to the next. Attempting to go back to undo decisions would turn the compilation process into something painfully slow (the number of paths that could be taken would be exponential).
* As always there are some exceptions but those are just exceptions, notably during overload resolution if a template is picked as the best candidate but substitution of type arguments fail, it is discarded and the next best candidate is chosen.

std::bind and winsock.h bind confusion

I'm working on a very large project and in one file we all of the sudden got a compile-time error where the compiler seems to think that our call to winsock.h bind() is actually a call to std::bind(). It seems that somewhere in a include file there is using namespace std code snippet. We could try and find where these using namespace std are in use and remove them, but perhaps there is a better way to do this?
You can change your calls to use ::bind() to specify the global namespace.
Yes, this is unfortunate. As I described at http://gcc.gnu.org/ml/libstdc++/2011-03/msg00143.html the std::bind template is a better match unless you use exactly the right argument types:
The problem is that the socket bind() function has this signature:
int bind(int, const sockaddr*, socklen_t);
so the call in the example using a non-const pointer finds that the
variadic template std::bind is a better match. The same would happen
if the third argument was any integral type except socklen_t.
Your code would work with GCC because I added a conforming extension to GCC's std::bind to prevent this ambiguity, by removing std::bind from the overload set if the first argument is "socket-like", which I defined using is_integral and is_enum. That doesn't help with other implementations though.
Removing the using namespace std; is a good idea anyway, but may not be entirely sufficient, because an unqualified call to bind() that happens to use a type defined in namespace std (such as std::size_t) could still find std::bind by argument dependent lookup. Jonathan Potter's answer is the best way to ensure you get the right function: qualify it as ::bind.

Why is the "using" directive still needed in C++11 to bring forward methods from the base class that are overloaded in the derived class

The example below gets the following compiled error:
test.cpp: In function ‘int main(int, char**)’:
test.cpp:26:8: error: no match for call to ‘(Derived) (p1&)’
test.cpp:14:8: note: candidate is:
test.cpp:16:10: note: void Derived::operator()(const p2&)
test.cpp:16:10: note: no known conversion for argument 1 from ‘p1’ to ‘const p2&’
It was my understanding this was getting changed in C++11 so you weren't required to put the using statement in. Is that not correct? Is there some other way around this?
Example (Compiled with gcc 4.7 using --std=c++11):
#include <iostream>
#include <string>
using namespace std;
struct p1{};
struct p2{};
struct Base
{
void operator()(const p1&) { cout << "p1" << endl; }
};
struct Derived : public Base
{
void operator()(const p2&) { cout << "p2" << endl; }
//Works if I include: using Base::operator();
};
int main(int argc, char** argv)
{
p1 p;
p2 pp;
Derived d;
d(p);
d(pp);
}
To the best of my knowledge, no, this has not changed in C++11.
And the reason it has not changed is that this behavior is not an accident. The language works like this by design. There are advantages and disadvantages to it, but it's not something that just happened because the people on the standards committee forgot about it.
And no, there's no way around it. It's just how member lookup works in C++
It was my understanding this was getting changed in C++11 so you weren't required to put the using statement in. Is that not correct?
No, member functions can still be hidden in C++11.
Is there some other way around this?
Using declarations are the intended remedy.
Just to clarify the situation: I can't imagine this ever changing in C++. To even hope to make it a tenable change, you'd have to tighten up type safety to the point that it would no longer be compatible with C (e.g., you'd pretty much have to eliminate all implicit conversions).
The situation is fairly simple: right now, name lookup stops at the first scope found that includes at least one instance of the name being used. If that instance of the name doesn't match the way you tried to use the name, then compilation fails.
Consider the obvious alternative: instead of stopping searching at that point, the compiler continues searching out scopes, created essentially an overload set of all those names, and then picked the one that matched the best.
In a case like this, a seemingly trivial change at an outer scope could (completely) change the meaning of some code, quite unintentionally. Consider something like this, for example:
int i;
int main() {
long i;
i = 1;
std::cout << i;
return 0;
}
Under the current rules, the meaning of this is clear and unequivocal: the i=1; assigns the value 1 to the i defined local to main.
Under the revised rules, that would be open to question -- in fact, it probably shouldn't be the case. The compiler would find both instances of i, and since 1 has type int, it should probably be matched up with the global i instead. When we print out i, the compiler finds an overload that takes a long, so it prints out the local i (which still contains garbage).
Note that this adds another wrinkle though: the cout << i; would be referring to the local i because there was an overload that could work with it. So instead of the type of the variable controlling the overload that was used, you'd have the available overloads also controlling the variable that was used. I'm not sure, but I'd guess this makes parsing much more difficult (quite possibly an NP-hard or NP-complete problem).
In short, any code that (intentionally or otherwise) used almost any kind of implicit conversion at an inner scope, this seemingly unrelated changes at outer scopes could suddenly change the meaning of that code completely -- and as in the example above, easily break it quite thoroughly in the process.
In the case above, with only a half dozen lines of code, it's pretty easy to figure out what's going on. Consider, however, what happens when (for example) you define a class in a header, then include that header into some other file -- the compiler looks at the other code where you included the header, find a better match, and suddenly code you swore was thoroughly vetted and tested breaks most spectacularly.
With headers, it would (or at least could) get even worse though. You define your class, and include the header into two different files. One of those files defines a variable, function, etc. at outer scope and the other doesn't. Now code in one file using name X refers to the global, while code in the other file refers to the local, because the global doesn't happen to be visible in that file. This would completely break modularity, and render virtually all code completely broken (or at least breakable).
Of course, there would be other possibilities that might not be quite this broken. One possibility would be to eliminate all implicit conversions, so only a perfect type match would ever be considered. This would eliminate most of the obvious problems, but only at the expense of completely breaking compatibility with C (not to mention probably making a lot of programmers quite unhappy). Another possibility would be to search like it does now, stopping at the first scope where it found a match -- then continuing to outer scopes if and only if compilation was going to fail if it used that name at the inner scope.
Either of these could work, but (at the very least) you'd need quite a few restrictions to keep them from leading to almost insane levels of confusion. Just for example, consider something like a =1; a = '\2'; Right now, those must refer to the same variable -- but with the first of these rules, they wouldn't.
With some special cases, you could probably eliminate that particular oddity too -- for example, use the current rules for looking up variable names, and new/separate rules only for function names.
Summary: the simple/obvious way to do this would create a language that was almost irretrievably broken. Modifications to prevent that would be possible, but only at the expense of throwing away compatibility with both C and essentially all existing C++ code. The latter might be possible in a brand new language, but for a language that's already well established like C++ (especially on that became established largely based on backward compatibility -- C++ again).