如何使用模板来确定适当的参数传递方法?

luk*_*uke 4 c++ templates type-traits

据我所知,当一个对象传递给一个比寄存器大的函数时,最好将它作为(const)引用传递,例如:

void foo(const std::string& bar)
{
    ...
}
Run Code Online (Sandbox Code Playgroud)

这避免了必须执行可能昂贵的参数副本.

但是,当传递适合寄存器的类型时,将其作为(const)引用传递最多是冗余的,最坏的情况是:

void foo(const int& bar)
{
    ...
}
Run Code Online (Sandbox Code Playgroud)

我的问题是,当我使用需要传递任何类型的模板化类时,我想知道如何充分利用这两个世界:

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);             
};
Run Code Online (Sandbox Code Playgroud)

是否有模板决策方法允许我选择正确的类型?可以让我做的事,

void bar(const_nocopy<T>::type baz);
Run Code Online (Sandbox Code Playgroud)

根据类型选择更好的方法?


编辑:

经过大量的定时测试后,两个通话时间之间的差异是不同的,但非常小.对于我的情况,解决方案可能是一个可疑的微优化.尽管如此,TMP仍然是一项有趣的心理锻炼.

Mar*_*utz 11

使用Boost.CallTraits:

#include <boost/call_traits.hpp>

template <typename T>
void most_efficient( boost::call_traits<T>::param_type t ) {
    // use 't'
}
Run Code Online (Sandbox Code Playgroud)


EFr*_*aim 6

如果变量复制时间很重要,那么编译器很可能会内联该模板的实例,而const引用的东西也同样有效.

从技术上讲,你已经给了自己一个答案.

只需专门no_copy<T>针对所有nocopy类型的模板.

template <class T> struct no_copy { typedef const T& type; };

template <> struct no_copy<int> { typedef int type; };
Run Code Online (Sandbox Code Playgroud)

  • 我想boost会有一个is_pod <T>特性来避免做所有这些专业化吗? (2认同)