The problem is the following: I have a rather large template function (about 200 lines) that must run very efficiently. However, in a particular line I need to specialize the function depending on the type. I do not know what is the best efficent way to solve this. Here are some ideas:
if (typeid(T) == typeid(some_type))
, but I have doubts that this is done in compile time since comparing typeid
's is not constexpr
. Let me know if I am wrong.constexpr static
function in the classes used as template types. However, this moves the code in a place I do not want it to be.I am missing any better way of doing it? How would you do this? I am using C++14.
I believe this is the syntax you're looking for
/* 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 your if
statements also had an else
you can do this instead
// 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 ...
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.