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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With