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.
The standard says in [temp.res]/8
No diagnostic shall be issued for a template definition for which a valid specialization can be generated. 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. ... [ Note: If a template is instantiated, errors will be diagnosed according to the other rules in this Standard. Exactly when these errors are diagnosed is a quality of implementation issue. — end note ]
There is no possible way to instantiate your function template that will compile, so the template definition is ill-formed and so the compiler is allowed (but not required) to reject it even if it isn't instantiated.
You could make it work like this:
template<typename T>
struct foobar : std::false_type
{ };
template <typename T>
inline T getValue(AnObject&)
{
static_assert( foobar<T>::value , "this function has to be implemented for desired type");
}
Now the compiler cannot reject the function template immediately, because until it is instantiated it doesn't know whether there will be a specialization of foobar
that has value == true
. When instantiated the relevant specialization of foobar<T>
will be instantiated and the static assertion will still fail, as desired.