简体   繁体   中英

Type independent code in templates

I am wondering what happens if the compiler instantiates a template function (or methods of a class template). Look at the following (senseless) example:

template <typename T> T DoSomething(T t)
{
   int i = ToInt<T>(t);
   string s = ToString<T>(t);

   cout << i << endl;
   // ... some more non-type specific code
   cout << s << endl;

   return DoLast<T>(t);
}

Only the first two lines and the last line do something on T taking its actual type into account. The code on between isn't type specific. Now I do this:

DoSomething<int>(1);
DoSomething<double>(1);

AFAIK this causes the compiler to instantiate the template two times at compile time which means it creates copies of both, the type specific code and the non-type-specific code. However the non-type-specific code doesn't need to be duplicated since it is independent from T.

Should I optimize this manually, moving the type independent code in a separate function or is there anything in the C++ standard or in compiler optimizers (especially VS) I can rely on?

EDIT: Regarding optimization... I am aware of the time vs memory tradeoff. I assume most optimizers try to balance both according to their settings. My question mainly is about a big portion of type independent code and a small type specific part where probably an additional call would be a good deal.

As with any performance and optimisation question, the only way to get a definite answer for your case is to implement both, profile, and compare the results.

Still, I would say that what you think of as "optimisation" may not actuall be one. One of the very important optimisations optimisers do nowadays is call inlining —that's precisely the opposite of what you want to do. Generally, performance is improved by copying function bodies into the call site and eliminating the function call overhead. Of course, this leads to massive code multiplication, but the optimisers know when this matters. Most of the time, the increase in code size does not affect performance at all.

You should look at the the assembly of your compiler compilation to find out what is being done.

Having said that, chances are that the type independent code makes for a standalone reusable package, so anyway it probably makes sense to put it in a separate function whatever the cost or profit could be.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM