最も安価な引数の型を決定するために、コンパイル時の方法

cppguy:

私はルックスがこれを気に入っていることのテンプレートを持っています

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

引数の型がブールまたはcharのような些細である場合はconst参照を使用して回避するために精通したテンプレートメタプログラミングの方法はありますか?お気に入り:

Foo(stl::smarter_argument<T>::type t) : _t(t) {}
n314159:

私は右のタイプの形質があると思います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&>;

おすすめ

転載: http://43.154.161.224:23101/article/api/json?id=369296&siteId=1