问题如下:我有一个相当大的模板函数(大约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 ...
}