如何在编译时专门化大型模板函数中的小部分
How to specialize a small part in a large template function in compile time
问题如下:我有一个相当大的模板函数(大约200行(,必须非常高效地运行。但是,在特定的行中,我需要根据类型专门化函数。我不知道解决这个问题最有效的方法是什么。以下是一些想法:
- 我显然可以使用
if (typeid(T) == typeid(some_type))
,但我怀疑这是否在编译时完成,因为比较typeid
的不是constexpr
。如果我错了,请告诉我 - 我可以将这些行移到用作模板类型的类中的
constexpr static
函数中。但是,这会将代码移动到我不希望的位置 - 我可以复制这200行。好吧,我们不要那样做
我错过了更好的方法吗?你会怎么做?我正在使用C++14。
我相信这就是您要查找的语法
/* pass parameter by reference in case you wanna change it */
inline void do_something(some_type &x/* , other parameters that any of the functions might need */)
{
++x; /* example, you can do anything */
}
inline void do_something(some_other_type &y/* , other parameters that any of the functions might need */)
{
y = y * y; /* example, you can do anything */
}
template<typename T> void very_large_function(T t)
{
// ... common code ...
do_something(t);
// ... more common code ...
}
如果你的if
语句也有else
,你可以这样做,而不是
// final else
template<typename T>
inline void do_something(T &t) {
t = t * 2; // example
}
inline void do_something(some_type &x)
{
++x; // example
}
inline void do_something(some_other_type &y)
{
y = y * y; // example
}
template<typename T> void very_large_function(T t)
{
// ... common code ...
do_something(t);
// ... more common code ...
}
相关文章:
- 构造函数的部分模板专用化
- 函数模板部分专业化-有什么解决方法吗
- 如何在编译时专门化大型模板函数中的小部分
- C++具有可变参数包的函数的部分模板参数推导会在 Clang 和 MSVC 中产生不明确的调用
- C 11:可以默认默认构造函数导致部分初始化类
- 具有可变参数的类成员函数模板部分专用化
- C++ 类析构函数删除部分但不是全部成员数据
- 对于需要其他模板参数的类型函数的部分模板专业化
- 特定成员函数的部分专业化
- 成员函数的部分模板专用化:"prototype does not match"
- 函数模板部分专用化的解决方法
- 不允许函数模板部分专用化'swap<T>'
- C++:如何在模板类中对模板函数进行部分专用化
- C++函数模板部分专用化
- 如何基于作为 STL 容器的模板参数模拟所选成员函数的部分专用化
- 具有递归可变参数模板的函数的部分模板专用化的替代方案
- 模板类中函数的部分专用化
- 声明函数第二部分
- 可变模板成员函数的部分专门化
- 为什么c++标准不允许函数模板部分特化