This question already has answers here:
ambiguous call in template error
(4 answers)
Closed 6 years ago.
I am trying to use c++ template generics with a void function,
The code:
#include <iostream>
using namespace std;
template <typename T>
inline void swap(T& x, T& y)
{
T temp = x;
x = y;
y = temp;
}
int main()
{
cout << "Swapper!" << endl;
int x, y;
cin >> x >> y;
swap(x, y);
cout << x << y;
cin.get();
return 0;
}
But it gives an error:
call of overloaded swap() is ambiguous
How do I remove this error?
The problem is using namespace std;. You should almost never use this line anywhere in your code. A good approach is to instead just quality all std names, i.e. write std::cout << "Swapper!" << std::endl; instead of cout << "Swapper!" << endl;.
In this particular case, your own swap function conflicts with std::swap, which you indirecty get via <iostream>. While std::swap is only guaranteed to exist in <algorithm> and <utility>, all C++ standard headers are allowed to pull in any other C++ standard headers.
So once you include any standard header, using namespace std; creates a potential conflict with all names in std.
You should remove using namespace std; because this namespace already contains a function called swap and the compiler doesn't know which one to choose. To be honest, you don't really need to write such a function yourself, it has already been done for you.
Another way is to rename your function to something other than swap.
Related
This question already has answers here:
Why Template Function call is ambiguous?
(3 answers)
Closed 5 years ago.
Here's my code trying to simply add 2 numbers.
#include <iostream>
#include <string>
using namespace std;
template<class first, class second>
first plus(first x, second y) {
return x + y;
}
int main() {
int a = 123;
int b = 21;
plus(a, b);
return 0;
}
The plus() gives me an error stating that it's "ambiguous". This is basically copied code I've seen in tutorials(where it has worked!) on templates so I'm really confused now.
Remove the using namespace std, you are colliding with std::plus
http://en.cppreference.com/w/cpp/utility/functional/plus
I've solved the issue either removing std namespace or changing the function name is all it takes!
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
I have searched this question in Google. I found some related question in stackoverflow.com and quora.com but i am still not clear about this two topics. Everyone says that we use #include<iostream> for input/output operation. Now, we take input using cin and print output using cout that means this two should be defined in #include<iostream>. But without using using namespace stdwe still can't take any input nor can print something on console. So, my questions are-
Where is cin and cout actually declared and defined? Is it in #include<iostream>or in namespace std?
If in #include<iostream>why should we use using namespace std?
If in namespace std why should we use #include<iostream?
After reading some article on the web and watching some videos on YouTube, I'm assuming cout and cin is defined in namespace std and the namespace std doesn't make any sense alone because it is defined in #include<iostream>. That's why we need to use them both. (Just my thought let me know if I am right or not.)
The purpose of this question is to be clear about this two facts. If you can help it would be great.
cin and cout are defined in the header iostream and in the namespace std. These concepts are orthogonal. iostream is a file name and std is a namespace used by the source code of that file.
As a way of keeping things organized, c++ provides namespaces. All of the standard library is defined within the namespace called std. Other libraries you might write or include may use their own namespace. For example, you might include a physics library in your project which wants to define the concept of algebraic vectors. By using it's own namespace (let's called if physlib) it can differentiate between it's vector (physlib::vector) and the standard vector (std::vector). Namespaces can also be nested to help organize large projects. For example, time keeping parts of the standard library are in std::chrono and file system related components are in std::filesystem.
The preferred way of using cin and cout is as following. :
#include <iostream>
int main()
{
std::cout << "Hello, World!\n";
return 0;
}
The statement using namespace std is simply an instruction to look in the namespace std by default. It allows you to omit the std:: part of using standard library components. It's generally regarded as a bad idea to used using namespace std.
Why should we use #include <iostream>
To bring the standard library's I/O functionality into our program.
while we are using using namespace std?
This allows us to use that functionality without writing std:: each time we do.
This is unrelated to the previous step. Writing only using namespace std does not bring I/O functionality into your program, and writing only #include <iostream> does not allow us to use that functionality without writing its components' names out in full (including the std:: prefix).
The #include directive determines what we can use;
The using namespace declaration determines how we can use it.
Perfectly fine:
#include <iostream>
int main()
{
std::cout << "Hello world!\n";
}
Also valid:
#include <iostream>
using namespace std;
int main()
{
cout << "Hello world!\n";
}
Not valid:
int main()
{
std::cout << "Hello world!\n";
}
And neither is this:
using namespace std;
int main()
{
std::cout << "Hello world!\n";
}
or this:
using namespace std;
int main()
{
cout << "Hello world!\n";
}
#include <iostrem> tells the compiler to pull in the contents of the header iostream. That header provides, among other things, declarations of the objects std::cin and std::cout. So the basic "Hello, world" program looks like this:
#include <iostream>
int main() {
std::cout << "Hello, world\n";
return 0;
}
Similarly, if you want to use std::vector, you tell the compiler about it with #include <vector>. Same thing for the rest of the standard library: whatever it is that you want to use, find out which header declares it and #include that header.
using namespace std; doesn't define any names for you. It tells the compiler to pretend that any names that have been defined in the namespace std are also defined in the scope where using namespace std; occurs. So that means that instead of writing std::cout you can write cout, and the compiler will figure out that you meant std::cout. Unless, of course, you've written something yourself with the name cout (or any other name that's in std and declared in a header that you've #included), in which case that using declaration makes the use of the name ambiguous. There is no good reason to write using namespace std;. Just use the right names for things: std::cout is clear and unambiguous.
Where is cin and cout actually declared and defined? Is it in #include<iostream> or in namespace std?
It's not or. cin and cout are declared in the iostream header file within the namespace std.
If in #include< iostream> why should we use using namespace std?
You shouldn't. Either fully qualify the global variables like std::cin or std::cout. There's a number of reasons why you shouldn't use using namespace std; (at least in header files).
If in namespace std why should we use #include<iostream>?
Because you need the declarations to compile your code.
iostream is part of the standard library, here is what the "iostream.h" file would look like if you were to implement it yourself:
namespace std{
// code about cin
extern ostream cin;
// code about cout
extern ostream cout;
}
(see c++ STL cout source code)
Where is cin and cout actually declared and defined? Is it in #include <iostream> or in namespace std?
So cin/cout are declared and define in the standard library under the
namespace std. This means that if you want to use it in your code you can do :
int main()
{
std::cout << "Hello";
}
If in #include<iostream> why should we use using namespace std?
You don't need using namespace std, you could call std::cout everywhere instead of cout, but you can see how this can make your code verbose and annoying to type.
using namespace std in your whole file is actually discouraged as it could have unintended effect, usually you could use only
using std::cout;
using std::cin;
where needed.
The reason the using is needed (or the need for explicitly writing std:cout , is imagine you have the following code:
#include <iostream>
namespace mycoolnamespace
{
class foo {
public:
foo& operator<< (const std::string& echo)
{
// do stuff
}
};
foo cout; // created a variable called cout
}
int main()
{
cout << "Hello";
// ^^^^ compiler can't know if you meant to use std::cout or mycoolnamespace::cout here!
// Potential fix:
std::cout << "Hello"
}
If in namespace std why should we use #include<iostream>?
By default not all function/classes from the standard library are included in your program, otherwise a simple "Hello world" program would give a lot of work to the compiler since it would need to parse all the existing classes/functions in the entire standard library. #include<iostream> tells the compiler that you need the functions/classes available in the standard library's iostream 'file'
This question already has answers here:
Why should I not #include <bits/stdc++.h>?
(9 answers)
Closed 6 years ago.
I was creating a basic tic tac toe game on c++,I got the desired game output without including bits/stdc++ header file,but when included there was an ambiguity for global variable count(which is in use in the below mentioned code). Please explain!
#include <iostream>
#include "unistd.h"
#include <cstdlib>
#include<bits/stdc++.h>
using namespace std;
char a[3][3];
int count=0;
char player_flag ='X';
void init()
{
a[0][0]='1';
a[0][1]='2';
a[0][2]='3';
a[1][0]='4';
a[1][1]='5';
a[1][2]='6';
a[2][0]='7';
a[2][1]='8';
a[2][2]='9';
}
void show()
{
for(int i=0;i<3;i++)
{ for(int j=0;j<3;j++) cout<<a[i][j] << " " ;
cout << "\n" ;
}}
void entry(int n,char player_flag)
{
for(int i=0;i<3;i++)
{ for(int j=0;j<3;j++)
{ if(n==(i*3+j+1))
{if(a[i][j]=='X'||a[i][j]=='O')
{ int n;
cout<<"invalid entry enter another position\n";
cin>>n; entry(n,player_flag);
}
else a[i][j]=player_flag;
}}}}
void turn()
{
if(player_flag=='X') player_flag='O';
else player_flag ='X';
}
void check()
{ int i,j;
for(i=0,j=0;j<3;i=0,j++)
{if(a[i][j]==a[i+1][j]&&a[i+1][j]==a[i+2][j]) {cout<<"\n"<<a[i][j]<<" wins \n"; exit(0);}}
for(i=0,j=0;i<3;j=0,i++)
{if(a[i][j]==a[i][j+1]&&a[i][j+1]==a[i][j+2]) {cout<<"\n"<<a[i][j]<<" wins \n"; exit(0);}}
if(a[0][0]==a[1][1]&&a[1][1]==a[2][2])
{cout<<"\n"<<a[0][0]<<" wins";exit(0);}
else if(a[0][2]==a[1][1]&&a[1][1]==a[2][0])
{cout<<"\n"<<a[0][2]<<" wins";exit(0);}
else if(count>=9){ cout<<"\nits a draw\n"; exit(0);}}
int main()
{ init(); show();
while(1)
{ int n; count++;
cout<<"player "<<player_flag<<" turn: enter position to put \n"; cin>>n;
entry(n,player_flag);
system("clear");
show();
check();
turn();`
}}
error: reference to ‘count’ is ambiguous
else if(count>=9){ cout<<"\nits a draw\n"; exit(0);}}
This is one of many ambiguous count errors.
PS: if bits/stdc++ is not included then its works fine,error pops out only when bits/stdc++ is used. Any reply is encouraged, Thanks!
std::count is a function from the standard library.
http://www.cplusplus.com/reference/algorithm/count/
Since you use the namespace std , "count" can refer to either std::count or the variable count.
You need to either rename your variable, or stop using the std namespace.
You can also include only the c++ headers that you need instead of bits/stdc++.h which includes all of them.
I suspect count is in std namespace somewhere.
Remove the line
using namespace std;
Use the namespace specifier std:: wherever you need it explicitly.
You should not use
#include<bits/stdc++.h>
anyway. Use headers that are part of the standard.
PS
From the answer by #CFrugal:
std::count is a function from the standard library.
http://www.cplusplus.com/reference/algorithm/count/
The files in the bits/ directory are implementation details not to be included in your programs directly. They are included indirectly by the normal includes like <vector> and <iostream>. Since it's an implementation detail, it's allow to make assumptions about the context in which it's included and presumably your include location violates one of those assumptions.
Just include the normal standard header for the functionality you need instead of a bits file.
Upon reading your question a second time it looks like you may also have a second problem: using namespace std bringing the std::count function into the global namespace, which collides with your global int count. To fix this consider using specific functions from standard instead of the entire namespace (using std::cout;), or rename your count variable, or don't declare it at global scope.
Why is the following code illegal?
#include <iostream>
using namespace std;
namespace what {
void print(int count) {
cout << count << endl;
}
}
void what::print(const string& str) {
cout << str << endl;
}
int main() {
what::print(1);
what::print("aa");
return 0;
}
The error I get when compiling with clang and -std=c++14 is
error: out-of-line definition of 'print' does not match any declaration in namespace 'what'
I know the fix to the problem but I am wondering why the compiler thinks that I am trying to define the function (print) instead of overload it.
The reason it is not working for you is because the syntax
void what::print(const string& str)
is basically saying
inside the what namespace, define the print function here
If you want to define a function outside of its namespace, you must declare it in the namespace beforehand.
§13.1 of the standard states, "When two or more different declarations are specified for a single name in the same scope, that name is said
to be overloaded."
Overloads of a function must be in the same scope of each other. It is just how the language works.
This is a question regarding the default global namespace in C++. I have the following code that compiles and runs properly using g++ clang-500.2.79.
#include <string>
#include <iostream>
using std::string;
using std::endl;
using std::cout;
bool is_palindrome(const string& str){
return equal(str.begin(), str.end(), str.rbegin());
}
int main(){
cout << "Hello is a palindrome: " << is_palindrome("Hello") << endl;
cout << "madam is a palindrome: " << is_palindrome("madam") << endl;
return 0;
}
My questions is, why does this code compile properly? I forgot to put #include <algorithm> and using std::equal at the beginning of my file. So the expected behaviour is for the compiler to complain.
The example at http://en.cppreference.com/w/cpp/algorithm/equal confirms that I should be using std::equal.
To investigate this further, I tried to track down exactly which version of the equal() function was being called. Being a relative newbie to C++ I don't know exactly how to do this either. I tried,
cout << "The function is: " << equal << endl;
Which generated a compiler error with some interesting information:
/usr/include/c++/4.2.1/bits/stl_algobase.h:771:5:
note: 'std::equal' declared here
Try as I might, I can't find information about stl_algobase (or more probably, I most likely don't understand what I've found). Is stl_algobase a set of functions that are automatically included in the global namespace?
A further questions is: What is the proper way to track (code or otherwise) down which function is being called when you are dealing with potentially overloaded or template functions in C++?
equal is in the std namespace. What you are seeing is argument dependent lookup (ADL). Because the arguments are in the std, the name lookup for equal considers that namespace too.
Here's a simplified example:
namespace foo
{
struct Bar {};
}
namespace foo
{
void bar(const Bar&) {}
void bar(int) {}
}
int main()
{
foo::Bar b;
foo::bar(b); // OK
bar(b); // ADL, OK
foo::bar(42); // OK
bar(42); // No ADL: error: 'bar' was not declared in this scope
}