Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
347 views
in Technique[技术] by (71.8m points)

c++ - static_assert fails compilation even though template function is called nowhere

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.

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...