gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 09:13:29 24 4
gpt4 key购买 nike

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

template <typename T> class Foo
{
public:
Foo(const T& t) : _t(t) {}
private:
const T _t;
};

在参数类型像 bool 或 char 这样微不足道的情况下,是否有一种精明的模板元编程方法可以避免使用 const 引用?喜欢:
Foo(stl::smarter_argument<T>::type t) : _t(t) {}

最佳答案

我认为正确的类型特征是 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;
};

编辑:

以上仍然有点老派,感谢@HolyBlackCat 提醒我这个更简洁的版本:
template<class T>
using smarter_argument_t = std::conditional_t<std::is_scalar_v<T>, T, const T&>;

关于c++ - 一种确定成本最低的参数类型的编译时方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60586167/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com