I have been using using std::cout; or using std::cin, etc., to introduce the names successfully to a source file and use them further in the functions of the file. I tried to do the same with std::string::size_type and ended up getting 'error: using-declaration for member at non-class scope' in gcc and 'error: not a valid using-declaration at non-class scope' in MSVC compiler.
Here is the link to the code I have written : https://onlinegdb.com/-c6sJuZdrV.
Following is the relevant excerpt from it.
#include <iostream>
#include <string>
using std::cout;
using std::cin;
using std::endl;
using std::string;
using std::string::size_type;
void Part_2()
{
string s1, s2;
cout << "Enter the first string" << endl;
cin >> s1;
cout << "Enter the second string" << endl;
cin >> s2;
size_type s1Size = s1.size();
size_type s2Size = s2.size();
}
I expected using std::string::size_type; to work just like using std::cout;. I found this Using declaration for a class member shall be a member declaration (C++2003) related question, but that's for a different use-case.
How can I make my code work?
A using-declaration:
can be used to introduce namespace members into other namespaces and block scopes, or to introduce base class members into derived class definitions
std::cin and std::cout are members of the std namespace, which is why you can import them into the global namespace with a using-declaration.
But std::string::size_type is not a namespace member, it is a class member, so you can't import it into the global namspace with a using-declaration, you can only import it into classes derived from std::string.
What you can do instead is use a type alias to introduce an alias to the class member type, like this:
using size_type = std::string::size_type;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With