Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

typedef equivalent for int

If I have a template container, I can use a typedef to let me lookup the type at compile time:

template <typename T>
struct MyList {
    typedef T Type;
    T get_front() const;
    // ...
};

MyList<char> char_list;
MyList<char>::Type front = char_list.get_front();

In this case you could declare char front = char_list.get_front(); instead, but sometimes this can be useful (e.g. template classes that contain other template classes).

In my case, the template doesn't specify a typename, but instead specifies an int (actually a std::size_t):

template <std::size_t N>
struct MyClass {
    // ...
};

Is there an equivalent of a typedef that I can declare inside the class that will allow me to get the value N outside of the class? Is this an appropriate place to use a static constant?

like image 639
user Avatar asked Oct 07 '22 03:10

user


1 Answers

The usual approach on modern compilers is:

static const std::size_t value = N;

Note that this will raise undefined-behavior if someone tries to take its address. This often means that the address of value could result in different locations for different translation units, but its undefined-behavior nevertheless.

Another approach usually used on older compilers, and which does not leave the door of undefined-behavior open, is emulation via enums:

enum { value = N };

Boost.Config offers the BOOST_STATIC_CONSTANT macro which will resolve to one or the other of the described approaches, based on compiler conformance. Its usage is:

BOOST_STATIC_CONSTANT( std::size_t, value = N );

It's reference can be found at http://www.boost.org/doc/libs/1_51_0/libs/config/doc/html/boost_config/boost_macro_reference.html#boost_config.boost_macro_reference.boost_helper_macros

like image 192
K-ballo Avatar answered Oct 10 '22 01:10

K-ballo