cschwan
cschwan

Reputation: 3363

When are class templates instantiated?

Suppose you have the following (ill-formed) program:

struct A
{
    A(int, int)
    {
    }
};

template <typename T>
class B
{
    B()
    {
        if (sizeof (T) == 1)
        {
            throw A(0); // wrong, A() needs two arguments
        }
    }
};

int main()
{
    return 0;
}

GCC compiles this program without any errors, clang++ refuses it with an error.

  1. Is it justified to say thats it is not a bug in GCC because the template isnt instantiated?
  2. What magic does clang do to find this error?
  3. What does the C++ standard say about those situations?

Upvotes: 11

Views: 262

Answers (2)

Steve Jessop
Steve Jessop

Reputation: 279255

The template is instantiated when used. However, it should be compiled when it's defined. Your code A(0) uses the name A, which doesn't depend on the template parameter T, so it should be resolved when the template is defined. This is called two-phase lookup. The way clang finds the error is simply by trying to resolve the call A(0) as soon as it sees it.

My version of GCC also compiles this code silently, even with -pedantic-errors. Both C++03 and C++11 say that no diagnostic is required, even though the program is ill-formed, so GCC conforms. This is 14.6/7 in C++03 and 14.6/8 in C++11:

If no valid specialization can be generated for a template definition, and that template is not instantiated, the template definition is ill-formed, no diagnostic required.

Upvotes: 11

AProgrammer
AProgrammer

Reputation: 52284

  1. Yes. When no valid specialization exist but the template isn't instantiated -- like here -- the program is ill-formed, but no diagnostic is required (14.6/8). So both clang and g++ are right.

  2. clang does more checks than g++ on the template declaration.

  3. See above.

Upvotes: 5

Related Questions