为什么要使用静态功能模板?

nn0*_*n0p 2 c++ static templates

我正在阅读Alex Graves的rnnlib。在他的代码中,有许多静态函数模板,它们不是类成员方法,而是定义为static,而有些则不是。(请参见下文)

的一些代码片段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);
    }
}
...
Run Code Online (Sandbox Code Playgroud)

为什么将这些全局功能模板中的一些定义为静态而有些则不定义呢?

Pao*_*o M 5

在这种情况下,static关键字是指静态链接,即该功能仅在定义它的翻译单元中可见。

现在,由于函数是在头文件中定义的,因此static关键字的作用是,编译器将在每个包含该头文件(并且实际上使用该函数)的翻译单元中为该函数生成代码。此外,该函数将被内联。

对于模板的功能,我会说,使用staticinline或没有关键字产生相同的结果; 实际上,在所有情况下,该函数都将内联,并且不会引发多定义错误。

因此,有趣的问题可能是“为什么要static 在非模板函数上使用 ”。