Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I use templates to determine the appropriate argument passing method?

As I understand it, when passing an object to a function that's larger than a register, it's preferable to pass it as a (const) reference, e.g.:

void foo(const std::string& bar)
{
    ...
}

This avoids having to perform a potentially expensive copy of the argument.

However, when passing a type that fits into a register, passing it as a (const) reference is at best redundant, and at worst slower:

void foo(const int& bar)
{
    ...
}

My problem is, I'd like to know how to get the best of both worlds when I'm using a templated class that needs to pass around either type:

template <typename T>
class Foo
{
  public:

    // Good for complex types, bad for small types
    void bar(const T& baz);   

    // Good for small types, but will needlessly copy complex types
    void bar2(T baz);             
};

Is there a template decision method that allows me to pick the correct type? Something that would let me do,

void bar(const_nocopy<T>::type baz);

that would pick the better method depending on the type?


Edit:

After a fair amount of timed tests, the difference between the two calling times is different, but very small. The solution is probably a dubious micro-optimization for my situation. Still, TMP is an interesting mental exercise.

like image 477
luke Avatar asked Dec 01 '22 07:12

luke


1 Answers

Use Boost.CallTraits:

#include <boost/call_traits.hpp>

template <typename T>
void most_efficient( boost::call_traits<T>::param_type t ) {
    // use 't'
}
like image 186
Marc Mutz - mmutz Avatar answered Dec 04 '22 13:12

Marc Mutz - mmutz