I'm reading Alex Graves's rnnlib.
In his codes there are many static function templates which are not class member methods but defined as static, while some are not.(see below)
Some code snipplets of Helpers.hpp:
...
// static
template <class R> static void sort(R& r)
{
sort(boost::begin(r), boost::end(r));
}
// static
template <class R> static void reverse_sort(R& r)
{
sort(boost::rbegin(r), boost::rend(r));
}
// non static
template <class R> pair<typename range_value<R>::type, typename range_value<R>::type> minmax(const R& r)
{
pair<typename range_const_iterator<R>::type, typename range_const_iterator<R>::type> p = minmax_element(boost::begin(r), boost::end(r));
return make_pair(*p.first, *p.second);
}
// static
template <class R> static void bound_range (R& r, const typename boost::range_value<R>::type& minVal, const typename boost::range_value<R>::type& maxVal)
{
for (typename range_iterator<R>::type it = boost::begin(r); it != boost::end(r); ++it)
{
*it = bound(*it, minVal, maxVal);
}
}
...
Why are some of these global function templates defined as static while some are not?
In that context, the static keyword refers to static linkage, i.e. that function will be visible only in the translation unit where it's defined.
Now, being that functions defined in a header file, the effect of the static keyword will be that the compiler will generate code for the function in every translation unit that include the header file (and that actually uses that function). The function, furthermore, will be inlined.
For template functions, I'd say that using static, inline or no keyword produce the same result; in fact, in all cases the function will be inlined and no multiple definition error will be raised.
So, the interesting question could be "Why to use static on non-template functions".
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