0

With using, an alias for a type can be defined and a unit of this type has the same size like an original instantation (1). A template however only weights 1 byte (2).

using aliasOfInt = int;

template<typename T>
struct intWrapper {
    using wrappedAliasOfInt = T;
};


int main() {
    // (1) --> 4B
    std::cout << "sizeof(aliasOfInt)      = " << sizeof(aliasOfInt) << std::endl;

    // (2) --> 1B
    std::cout << "sizeof(intAliasWrapper) = " << sizeof(intWrapper<int>) << std::endl;
}

In (2), is there a real type compiled or why is this only 1B?

http://cpp.sh/3eiry

TMOTTM
  • 3,286
  • 6
  • 32
  • 63
  • 3
    Make it an regular struct and you'd get the same result. – tkausl Jan 09 '21 at 22:46
  • 2
    How big do you expect your template to be, and why exactly? Just because I declare a `typedef` or a `using` as part of my class doesn't make it any bigger. Did you know that you could add a few million `typedef`s and `using`s to any class in C++, and its `sizeof` does not change? Why should it change? C++ does not work this way. It's not like it's adding any actual data that takes up any actual memory to store it, as part of the class or or struct. – Sam Varshavchik Jan 09 '21 at 22:49
  • 2
    What data members does `intWrapper` contain that would change its size? – Retired Ninja Jan 09 '21 at 22:49
  • A `using` type defined inside a class/struct doesn't occupy size in an object of that class/struct. – max66 Jan 09 '21 at 22:50
  • I was under the impression that by specialising the template in `main` with `intWrapper`, I'd be creating a real class. – TMOTTM Jan 09 '21 at 22:55
  • 1
    I don't understand why you think a "real class" object can't occupy one byte. It has no instance data. – StoryTeller - Unslander Monica Jan 09 '21 at 22:58

1 Answers1

4

The template is a red herring. It's a structure without data members, regardless of T. Since C++ does not allow sizeof(anything)==0, sizeof(intWrapper<int>) has to be greater than 0. This leaves size 1 as a natural choice.

MSalters
  • 173,980
  • 10
  • 155
  • 350