I came up with the idea of using decltype
to define static members in a .cpp file, and then using this macro:
#define DEFINE_SYMBOL(x) decltype(x) x
This way, for instance, if class Foo
declares static int bar
, I can do the following in foo.cpp:
DEFINE_SYMBOL(Foo::bar) = 1337;
This seems a bit "hacky", but it has the advantage of being resilient to changes in the original symbol type. For instance, if bar changes to unsigned in foo.hpp, I wouldn't need to change foo.cpp. It's also easier to read when the type of the member is complex.
However, if the static member is private, in Visual Studio 2015, Intellisense complains about using decltype (saying it's inaccessible). The complaint makes sense, although the program compiles just fine. Now, my question is, is Intellisense wrong, or is this usage of decltype not recommended (and why)?
Intellisense is incorrect, both gcc and clang compile a similar program and we can see the draft C++ standard section 11
[class.access] says:
All access controls in Clause 11 affect the ability to access a class member name from the declaration of a particular entity, including parts of the declaration preceding the name of the entity being declared and, if the entity is a class, the definitions of members of the class appearing outside the class’s member-specification. [ Note: this access also applies to implicit references to constructors, conversion functions, and destructors. —end note ] [ Example:
class A { typedef int I; // private member I f(); friend I g(I); static I x; template<int> struct Q; template<int> friend struct R; protected: struct B { }; }; A::I A::f() { return 0; } A::I g(A::I p = A::x); A::I g(A::I p) { return 0; } A::I A::x = 0; template<A::I> struct A::Q { }; template<A::I> struct R { }; struct D: A::B, A { };
Here, all the uses of A::I are well-formed because A::f, A::x, and A::Q are members of class A and g and R are friends of class A. This implies, for example, that access checking on the first use of A::I must be deferred until it is determined that this use of A::I is as the return type of a member of class A. Similarly, the use of A::B as a base-specifier is well-formed because D is derived from A, so checking of base-specifiers must be deferred until the entire base-specifier-list has been seen. —end example ]