Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

c++ - Forward declare a constexpr variable template

I tried to forward-declare a constexpr variable template like this:

template<typename>
constexpr std::size_t iterator_category_value;

The goal was to document that every specialization should be constexpr but I have to admit that I never checked whether it was legal or not and g++ was happy with it. However, when I tried to compile this spinnet with clang++ instead, I got the following error:

error: default initialization of an object of const type 'const std::size_t' (aka 'const unsigned long')
    constexpr std::size_t iterator_category_value;
                          ^
                                                  = 0

The error makes sense, and removing constexpr makes it disappear, so that's not a real problem. However, I am curious now: does the standard allow such a constexpr forward declaration for a variable template or is it illegal? g++ and clang++ seem to disagree and I would like to know where I should submit a bug report if needed.

Both of them complain for a forward-declared constepxr variable which is not a variable template, so the variable template context seems to be what makes the compilers disagree.

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

Clang is correct. The declaration of a variable template is an object declaration ([dcl.dcl]/9), hence it must provide an initializer as per [dcl.constexpr]/9:

A constexpr specifier used in an object declaration declares the object as const. Such an object […] shall be initialized.

There is effectively no way of "forward" declaring an object as constexpr in the first place, though; If constexpr is applied to the declaration of a variable, it shall be a definition ([dcl.constexpr]/1).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...