Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

struct vector works

Tags:

c++

struct

I did a mistake in my program, I wrote

struct vector<int> v;

instead of

vector<int> v;

but it seems that the compiler doesn't care: http://codepad.org/TCPb8p2u

Why does it work? Is there some differencies with or without struct?

like image 529
Ruggero Turra Avatar asked Apr 21 '26 22:04

Ruggero Turra


2 Answers

If you write class, it would also work.

class vector<int> v;

See this: http://www.ideone.com/EoJxk

This is actually old C style. The C++ Standard calls it elaborated-type-specifier in section §3.4.4.

The keyword struct (or class, enum) is sometimes used to remove ambiguities, or to make hidden names visible to the compiler. Consider the following example from the Standard itself (from section §9.1/2). Please notice that there exists a struct with name stat and with exactly same also exists a function:

struct stat {
    // ...
};
stat gstat; // use plain stat to define variable

int stat(struct stat*); // redeclare stat as function

void f()
{
    struct stat* ps; // struct prefix needed to name struct stat
    // ...
    stat(ps); //call stat()
    // ...
}

§9.1/2 says,

A class definition introduces the class name into the scope where it is defined and hides any class, object, function, or other declaration of that name in an enclosing scope (3.3). If a class name is declared in a scope where an object, function, or enumerator of the same name is also declared, then when both declarations are in scope, the class can be referred to only using an elaborated-type-specifier (3.4.4).

like image 135
Nawaz Avatar answered Apr 23 '26 11:04

Nawaz


This is a feature of C++ that's used to resolve ambiguity between a variable and type with the same name. I believe they're called 'elaborate type specifiers.'

You can use a keyword to tell the compiler exactly what you mean, when there would normally be ambiguity.

Take this for example:

int x = 0;
class x { };

// Compiler error! Am I refering to the variable or class x?
x y;

// This is okay, I'm telling the compiler which x I'm referring to.
class x y;

This can also be used to specify enums and unions, not just structs and classes, though you can only have one user-defined type with the same name.

like image 40
Collin Dauphinee Avatar answered Apr 23 '26 11:04

Collin Dauphinee



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!