简体   繁体   中英

How to access a header member type without scope resolution operator in C++?

I am learning C++, this may be a silly question.

I want to create a class for common type definitons and using it in many cpp files by inluding. Header is "CommonTypesCls.h":

class CommonTypesCls
{
public:     
    typedef unsigned int UINT32;
    typedef int INT32;
}

And I want to use these attributes in source.cpp like that:

#include "CommonTypesCls.h"
int main()
{    
    int a = sizeof(UINT32);
    return 0;
}

Is it possible to using a inclueded class' member type without scope resolution?

No, it's not possible unless you use a type alias.

using UINT32 = CommonTypesCls::UINT32;

But you shouldn't do that because a class is not a suitable place to collect type definitions.

Put them in the global scope or in a namespace instead.

Loooon ago, the C++ standard included namespace for exactly this purpose (btw, it appears you're re-inventing a wheel):

#include <cstdint>

namespace CommonTypesCls {
  using uint32 = std::uint32_t;
  using  int32 = std::int32_t;
}

int foo() {
  using namespace CommonTypesCls;
  uint32 a = 666;
}

If your types are specific to a particular class, for example dependent on a template parameters (such as std::vector<>::value_type ), then you must use the scope resolution operator somewhere, but you can create an alias:

template<typename Container>
void bar(Container const&container)
{
  using value_type = typename Container::value_type;   // scope resolution
  value_type temporary_storage[4];
  for(auto const&x : container) {
    /* do something with x and using temporary_storage */
  }
}

However, when using auto variable declarations, it is often not necessary to explicitly specify the type.

A class is generally the wrong way to provide common definitions: use a namespace .

Also, the particular definitions you appear to want, of fixed size integer types, are provided by <stdint.h> .

That said, you can use public and protected definitions from a class C unqualified in code in a class derived from C . But that would be using two generally wrong tools: a class to provide definitions, and inheritance to gain access. Still it can be appropriate in some cases, eg for providing access to the names in an enum type.

Sure:

#include "CommonTypesCls.h"
int main()
{
    typedef typename CommonTypesCls::UINT32 UINT32;
    int a = sizeof(UINT32);
    return 0;
}

Seriously though, not really.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM