一种确定成本最低的参数类型的编译时方法

cpp*_*guy 16 c++ stl

我有一个看起来像这样的模板

template <typename T> class Foo
{
public:
    Foo(const T& t) : _t(t) {}
private:
    const T _t;
};
Run Code Online (Sandbox Code Playgroud)

在参数类型像 bool 或 char 这样微不足道的情况下,是否有一种精明的模板元编程方法可以避免使用 const 引用?喜欢:

Foo(stl::smarter_argument<T>::type t) : _t(t) {}
Run Code Online (Sandbox Code Playgroud)

n31*_*159 13

我认为正确的类型特征是is_scalar. 这将按如下方式工作:

template<class T, class = void>
struct smarter_argument{
    using type = const T&;
};

template<class T>
struct smarter_argument<T, std::enable_if_t<std::is_scalar_v<T>>> {
    using type = T;
};
Run Code Online (Sandbox Code Playgroud)

编辑:

以上仍然有点老派,感谢@HolyBlackCat 提醒我这个更简洁的版本:

template<class T>
using smarter_argument_t = std::conditional_t<std::is_scalar_v<T>, T, const T&>;
Run Code Online (Sandbox Code Playgroud)

  • @TarekDakhran 标量包括不是基本的指针和枚举,在我看来应该按值传递。 (2认同)
  • 可以简化为“template &lt;typename T&gt; using smarter_argument = std::conditional_t&lt;std::is_scalar_v&lt;T&gt;, T, const T &amp;&gt;;”。 (2认同)