9

This question is about the relationship between templates and static integral constants in Visual Studio C++ 2013 with flag /Za. It has implications for the boost library.


First, let us check the code without templates:

struct easy
{
    static const int a = 5;
    const int b;

    easy( int b_ ) : b( std::max( b_, a ) )
    {}
};

const int easy::a;

int main()
{
    easy d_Easy( 0 );
    return 0;
}

According to the manual page for compiler option /Za: "Under the standard (/Za), you must make an out-of-class definition for data members". The example in that page and the code above declares the static constant within the class and specifies its value there. The need for the out of class definition is explained in this link.


Now, let us see the problem with templates.

template< class T >
struct problem
{
    static const int a = 5;
    const int b;

    problem( int b_ ) : b( std::max( b_, a ) )
    {}
};

template< class T >
const int problem< T >::a;

int main()
{
    problem< char > d_Bad( 666 );
    return 0;
}

When compiling with /Za, the linker throws an error "LNK2019: unresolved external symbol". That error does not appear with option /Ze.The major problem is that some boost libraries use BOOST_STATIC_CONSTANT and BOOST_NO_INCLASS_MEMBER_INITIALIZATION in code similar to the above snipet.


Hacking some:

template< class T >
struct fixed
{
    static const int a;
    const int b;

    fixed( int b_ ) : b( std::max( b_, a ) )
    {}
};

template< class T >
const int fixed< T >::a = 5;

int main()
{
    fixed< char > d_Good( 777 );
    return 0;
}

This code now compiles with /Za.

Questions:

1) What does the C++11 standard say about templates and static integral constants? Can/must they have an out of class definition but their value be provided in the class definition?

2) Does boost have some workarounds?


UPDATE

It is important to keep the std::max in the code because (I think) it tries to get the reference to its parameters. If one uses b_<a then the compiler simply optimizes those constants away.

10
  • "If one uses b_<a then the compiler simply optimizes those constants away." As it should, obviously. Using the references here changes nothing. Why would this be relevant?
    – sehe
    Jan 8, 2015 at 0:21
  • Perhaps the trailing paragraph of my answer is essential to your real question? If so, obviously you always need to separate the static member initialization into a separate translation unit.
    – sehe
    Jan 8, 2015 at 0:22
  • @sehe: it is relevant because I cannot compile boost::pool with /Za in Visual Studio C++13. I traced the culprit to the behavior in the question. After I find out who is responsible, I will report the bug either to the boost people or to the MS fellas.
    – Hector
    Jan 8, 2015 at 0:25
  • I've posted a near exhaustive comparison of {max,ternary}/{enum,static-field-in-class,static-field-out-of-class} in the comment at my answer. TL;DR I was right: it doesn't matter. The compiler inlines the std::max variant just the same (as it should)
    – sehe
    Jan 8, 2015 at 0:43
  • @sehe: Thank you. What you did proves that the compilers in that page do not show an error. But then, those compiles have no problem with: #include <iostream> struct A { static const int a = 5; A(){ std::cout << & a;} }; int main() { A d_A; return 0; }
    – Hector
    Jan 8, 2015 at 1:46

2 Answers 2

6
+250

First of all, a declaration of a static data member in class is never a definition. If you odr-use that variable, a definition must be present - out of class, of course.

std::max does indeed odr-use a, as its parameters are references, and variables are odr-used if a reference is bound to them ([basic.def.odr]/3). (That is indeed a problem with max - it shouldn't odr-use a, really.)
In @sehe's answer, he is using the ternary operator directly, avoiding an odr-use as the lvalue-to-rvalue transformation is immediately applied and yields a constant expression.

  1. It's quite simple. When the definition of a static data member of a class template is needed, i.e. when that member is odr-used as in your case, the (namespace scope) definition is instantiated. [temp.inst]/2:

    Unless a member of a class template or a member template has been explicitly instantiated or explicitly specialized, the specialization of the member is implicitly instantiated when the specialization is referenced in a context that requires the member definition to exist; in particular, the initialization (and any associated side-effects) of a static data member does not occur unless the static data member is itself used in a way that requires the definition of the static data member to exist.

    And the definition is done exactly as you did it. [temp.static]/1:

    A definition for a static data member or static data member template may be provided in a namespace scope enclosing the definition of the static member’s class template.

    [ Example:

    template<class T> class X {
        static T s;
    };
    template<class T> T X<T>::s = 0;
    

    The initializer can be supplied at the declaration in-class when the member is of const integral type, but that doesn't affect the semantics of the ODR in this respect. The definition is still required in the same way and written just as you did it.

Hence it seems what you see is solely a VC++ bug.

8
  • "std::max does indeed odr-use a, as its parameters are references" Are you sure that is sufficient to require a definition? coliru.stacked-crooked.com/a/1d0913fc7bc14b31
    – dyp
    Jan 11, 2015 at 3:07
  • Ah, it seems the set of potential results of any function call expression is empty; therefore it is ODR-used. Right? (A max function that takes by value would not require this, since there's a sub-expression that applies the l-t-r conversion to ex.)
    – dyp
    Jan 11, 2015 at 3:19
  • I reported it as a bug.
    – Hector
    Jan 11, 2015 at 9:53
  • @dyp My argumentation is easier: In a call f(x) where the l-t-r conversion is not applied to x, consider the id-expression x. Let's say ex is the expression x. The expression e is then also x - and e does not meet the requirement in the very last part of the first sentence of [basic.def.odr]/3 - neither is the l-t-r conversion applied, nor is it an unevaluated operand. Does that seem about right?
    – Columbo
    Jan 11, 2015 at 10:57
  • 1
    @dyp Yeah, that's what I meant. The only expression e for which ex is an element of the potential results of e is x itself.
    – Columbo
    Jan 11, 2015 at 15:34
2

A workaround that I used for a long time and recently became more useful in c++11:

Live On Coliru

struct easy
{
    enum : int { a = 5 };
    int b;

    constexpr easy(int b_) : b(b_<a? a : b_)
    {}
};

It became more useful because you can now specify the underlying type:

struct Container
{
    enum special_position : size_t { npos = size_t(-1), at_bof = 0 };
};

Of course it's limited to (userdefined/primitive) integral types.


Externally defined constants may have the benefit that they could actually be changed by only recompiling the translation unit that defines the value.

15
  • don't you need enum class if you want to specify the underlying type?
    – vsoftco
    Jan 8, 2015 at 0:06
  • 1
    @vsoftco no (at least not on my compilers)
    – sehe
    Jan 8, 2015 at 0:07
  • @vsoftco: The class part makes it strongly typed. Without it, the declarations spill out to the container structure.
    – Hector
    Jan 8, 2015 at 0:08
  • warning: scoped enums only available with -std=c++11 or -std=gnu++11 if you compile with g++ -pedantic
    – vsoftco
    Jan 8, 2015 at 0:08
  • 1
    I think it should be irrelevant: max vs. ternary vs. ternary, static member vs. max, static member vs. max, static member, out-of-class vs. ternary, static member, out-of-class . Literally the only difference in generated code will be the presence/absense of easy::a in the data segment.
    – sehe
    Jan 8, 2015 at 0:40

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.