Warm tip: This article is reproduced from serverfault.com, please click

static_assert fails compilation even though template function is called nowhere

发布于 2013-01-31 23:55:00

I use g++ 4.6.3, (currently default package for ubuntu 12.04) with the flag c++0x, and I stumble across this:

template <typename T>
inline T getValue(AnObject&)
{
    static_assert(false , "this function has to be implemented for desired type");
}

with the compilation error:

static_assertion failed "this function has to be implemented for the desired type"

even though I don't call this function anywhere yet.

Is it a g++ bug ? Shouldn't this function be instanciated only if it is called somewhere in the code.

Questioner
Stephane Rolland
Viewed
0
Andy Prowl 2013-02-01 08:07:16

That's because the condition does not depend in any way on the template parameters. Therefore, the compiler can evaluate it even before instantiating that template, and produces the associated compilation error message if it the evaluation yields false.

In other words, this is not a bug. Although many things can only be checked once a template is instantiated, there are other validity checks that a compiler can perform even before. This is why C++ has a two-phase name lookup, for instance. The compiler is just trying to help you finding errors that are 100% likely to occur.