Boost logo

Boost :

Subject: Re: [boost] static in_class constants
From: Mateusz Loskot (mateusz_at_[hidden])
Date: 2010-03-13 13:23:45


Christian Henning wrote:
>> 2) I notice you saying that you're getting linker errors - that
>> should only happen if you're taking the address of the constants
>> somewhere - if that's a use case that you want to support, then you
>> need a definition for the constants somewhere - suitably guarded by
>> the right Boost.Config macros (sorry can't remember what off the
>> top of my head).
>
> I'm getting a compiler error with gcc 3.4.5. The compiler that comes
> with MinGW.

Is it compiler error or linker error?

I did a simple test of the construction you use with GCC 4.4.1
and I'm getting linker error:

#include <boost/config.hpp>
#include <cassert>

template<typename Property>
struct property_base
{
    typedef Property type;
};

struct pnm_image_type : property_base<int>
{
    typedef pnm_image_type self_type;
    BOOST_STATIC_CONSTANT( type, _mono_asc = 1 );
};

int main()
{
    pnm_image_type imt;
    int const& r = pnm_image_type::_mono_asc;
    assert(1 == r);
    int const* p = &pnm_image_type::_mono_asc;
    assert(1 == *p);
}

gcc.link bin/gcc-4.4.1/debug/static_const
bin/gcc-4.4.1/debug/static_const.o: In function `main':
/home/mloskot/workshop/boost/constants/static_const.cpp:17: undefined
reference to `pnm_image_type::_mono_asc'
/home/mloskot/workshop/boost/constants/static_const.cpp:18: undefined
reference to `pnm_image_type::_mono_asc'
collect2: ld returned 1 exit status

    "g++" -o "bin/gcc-4.4.1/debug/static_const" -Wl,--start-group
"bin/gcc-4.4.1/debug/static_const.o" -Wl,-Bstatic -Wl,-Bdynamic
-Wl,--end-group -g

...failed gcc.link bin/gcc-4.4.1/debug/static_const...
...failed updating 1 target...
...updated 1 target...

This can be fixed, inconveniently, by adding external definition:

struct pnm_image_type : property_base<int>
{
    typedef pnm_image_type self_type;
    BOOST_STATIC_CONSTANT( type, _mono_asc = 1 );
};
const int pnm_image_type::_mono_asc;

>> And finally, given that your constants look like enumerated values,
>> is there actually a pressing need not to make them an anonymous
>> enumerated type in this case?
>
> I know about using enums for such a case. But it used to be a matter
> of taste since MS compiler works just fine.

Works well with in-class definition of constants from Visual C++ 7.1
(2003), but previous versions do not support it such definitions at all.

AFAIR, GCC 3.3.x has problems with integral constants defined
within classes, but in 3.4.x it should work well.

Best regards,

-- 
Mateusz Loskot, http://mateusz.loskot.net
Charter Member of OSGeo, http://osgeo.org

Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk