A C++ template is just "grammar safe" and not type safe first?

C++ templates are checked at least twice. First, when a template is declared & defined, second when it is instantiated. After a template successfully instantiated it is in a type safe state. My question is that what is the name of the state where a template is in when a template is successfully declared & defined? If I compare macro with templates, is it true that after a successful macro "instantiation" the code is type safe?

#define BAR(x) return x;
                        ^
// BAR is preprocessor-grammar-safe here?

struct Bar
{
  static void bar() {}
};
  ^
// Bar is type safe at this point?

template<typename T>
void foo()
{
  T::bar();
}
 ^
// foo is C++-grammar safe at this point?

int main()
{
  foo<Bar>();
             ^
  // foo is type safe at this point?

  foo<int>();
         ^
  // foo is ill-formed here?

  BAR(0);
         ^
  // BAR is type safe at this point?

  return 0;
}

Upvotes: 1

Views: 1183

Answers (3)

user2249683
user2249683

Reputation:

You just miss a little point: Macro processing is text processing (done before compilation)

Assuming preprocessing has generated valid code: A template can be successfully declared. Instantiation (definition) might fail, however.

Essentially BAR(0); is not type safe (exaggerating a bit here) !

Upvotes: 1

seand
seand

Reputation: 5286

Think of a C++ template as a macro on steroids and having syntactical knowledge. ex.

template<typename T> 
void func(T t) {
  t.foo();
  ...

Nothing declares the fact that T must have a foo() function; This distinguishes C++ templates from things like Scala type parameters. I believe newer C++ versions have added some support for this. You basically let the compile "try" using the t.foo() and if there's no such function it fails to compile.

Upvotes: 3

Kerrek SB
Kerrek SB

Reputation: 477010

A template is a template.

A type is a type.

Types may be obtained by specializing templates ("instantiating" in colloquial speech).

Templates and types have names. Types that are unions and classes must be declared, and defined in order to be complete. Templates must be declared, and defined in order to specialized.

That's all I can think of, and that should be enough vocabulary to talk about most aspects of the type system of C++ on a "first draft" kind of level.

Upvotes: 3

Related Questions