Reputation:
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?
Upvotes: -1
Views: 241
Reputation: 145419
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, e.g. for providing access to the names in an enum
type.
Upvotes: 1
Reputation: 45474
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.
Upvotes: 2
Reputation: 14318
Sure:
#include "CommonTypesCls.h"
int main()
{
typedef typename CommonTypesCls::UINT32 UINT32;
int a = sizeof(UINT32);
return 0;
}
Seriously though, not really.
Upvotes: 0
Reputation: 66449
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.
Upvotes: 3