简体   繁体   中英

Way to pass argument to template function

Lets assume I have a template function

template <typename T>
void do_sth(T const&);

For some types ("small" and copyable) it would be better to pass an argument by value instead of reference.

So my question is: What is the simplest way to overload a function depending on the underlying type?

Remark: Best what I came to is using enable_if with some conditions of "simple" type. And I believe there's no such a type trait as "simple type" in the standard library. Correct me if I'm wrong. Moreover: Using enable_if gets complicated as a function takes more template arguments ( edited ) because template <typename T, typename U> void do_sth(T, U) would need 4 overloads: (value, value), (value, ref), (ref, value) and (ref, ref).

boost has call_traits :

template <typename T>
void do_sth(typename boost::call_traits<T>::param_type)

But one big issue is that T is no longer deducible
(and so you have to call it do_sth<int>(42) or do_sth<MyBigObj>(myBigObj) ).

So might be used for non template methods in template class:

template <typename T>
struct S
{
    void do_sth(typename boost::call_traits<T>::param_type);
};

But anyway, chances are that compiler actually inlines code, resulting in same generated code.

Don't do this. Template functions are inlined at the drop of a hat, and a reference to an x is an alias with no identity once the function is inlined.

Encourage the function to be inlined instead of doing a mess of SFINAE, unless and until you have proven this to be an important bottleneck.

After discovering this function is taking up more time than anything else you can optimize, test its improvement by manualy writing the by value version in a couple of key cases to ensure you actually get a benefit (I doubt you will).

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