Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

using with class & namespace differencies/ambiguity

Tags:

c++

c++11

I'm just curious why it is designed in that way with using directive. For 1) struct is treated like namespace and for 2) it is not:

struct foo
{
  using type0 = int;
};

namespace bar
{
  using type1 = int;
}

using bar::type1; 
using type0 = foo::type0; // 1)
using foo::type0;         // 2)

clang version 3.3 (branches/release_33 186829)
clang -std=c++11 test.cpp
test.cpp:13:12: error: using declaration can not refer to class member
using foo::type0;

~~~~~^

gcc version 4.8.1
c++ -std=c++11 test.cpp
test.cpp:13:12: error: ‘foo’ is not a namespace
using foo::type0;
like image 584
Artur Bac Avatar asked Dec 21 '22 02:12

Artur Bac


1 Answers

Classes are not namespaces; they have a strict scope. The name of a class member (when accessed outside of the class) must always be prefixed by the class name.

using isn't allowed to change that.

The reason #1 works is because you creating a type alias to the type declared in the class. That's what using name = typename; does. In this case, it's no different from a typedef.

#2 doesn't create an alias; that syntax expects to be given a name within a namespace to bring into the current namespace.

like image 144
Nicol Bolas Avatar answered Jan 05 '23 02:01

Nicol Bolas