我正在阅读 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);
}
}
...
为什么有些全局函数模板被定义为static,而有些则不是?
最佳答案
在这种情况下,static
关键字指的是静态链接,即该函数仅在定义它的翻译单元中可见。
现在,作为在头文件中定义的函数,static
关键字的作用是编译器将为包含头文件的每个翻译单元中的函数生成代码(以及实际上使用该功能)。此外,该函数将被内联。
对于模板函数,我会说使用static
、inline
或不使用关键字会产生相同的结果;事实上,在所有情况下,函数都将被内联,并且不会引发多重定义错误。
因此,有趣的问题可能是“为什么要使用 static
非模板函数”。
关于c++ - 为什么要使用静态函数模板?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29495678/