Michael
Michael

Reputation: 2773

Legal Function Parameters

While working with C++, I began wondering how code like sizeof(int) worked. I realize that sizeof is an operator, not a function, but it still got me wondering... is code like myFunc(double) legal? Can you pass just the pure type of something, like int or MyClass to a function? Admittedly, I can't see much applications for that, but I'm just wondering.

Upvotes: 3

Views: 177

Answers (2)

Lightness Races in Orbit
Lightness Races in Orbit

Reputation: 385264

Operators like sizeof work because the language says that they do.

Not everything is a construct like a function that you can overload or recreate yourself. You can't make your own operator that takes a type name, just like you can't make your own primitive type, or declaration syntax.

You could not re-write sizeof in your C++ program and use it there (though its underlying implementation within the compiler is often written in C++! that's at another layer of abstraction, though).

There's no magic here; just facts of life.

Upvotes: 2

Jashaszun
Jashaszun

Reputation: 9270

No, you can't. Arguments are expressions, and in C++ types are not expressions.

Templates are used for "type arguments", but they're only at compile-time. (See @Banex and @clcto, above.)

Upvotes: 3

Related Questions