为什么要使用静态函数模板
Why use static function template?
我正在阅读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
、inline
或不使用关键字都会产生相同的结果;事实上,在所有情况下,函数都是内联的,不会引发多重定义错误。
因此,有趣的问题可能是"为什么在非模板函数上使用static
"。
使用静态函数是指当我们的代码编译时,将执行静态代码。所以所有静态函数的链接都是在编译时完成的。
相关文章:
- C++17中函数模板中的静态数组初始化(MSVC 2019)
- 指向模板上下文中的成员函数或静态函数的指针
- 生成代码(在编译时)以调用模板的每个实例化的静态函数
- 生成模板实例列表并对其调用静态函数
- boost::bind 无法绑定到纯虚拟基类中定义的非静态函数模板成员类型
- 在执行 SFINAE 时访问模板派生类 (CRTP) 的静态函数时类型不完整
- 模板专用化与静态函数模板
- 使用函数模板中静态局部变量的地址作为类型标识符是否安全
- 静态函数作为类模板参数-导致可维护性问题
- C++ - 模板类 -> 静态函数 -> 静态函数指针的链接错误
- 使用g++编译时静态函数的模板专用化
- 使用类的静态函数模板成员的链接器错误
- 为什么要使用静态函数模板
- 模板类中静态函数或指针的作用域解析
- 在cuda中使用静态成员函数模板结构的另一种方法
- 成员模板静态函数的类型特征
- C++模板,静态函数专用化
- 为什么其中一个模板静态函数有效,而另一个不起作用
- 在依赖范围内调用静态函数模板
- 静态函数模板和MISRA C++