簡體   English   中英

C++ 將參數包傳遞給類

[英]C++ passing parameter pack to class

我想要一個類,它可以獲取相同類型的 Ctor 無限參數,並將它們存儲到一個向量中。 它應該是這樣的:

class A(int a, int b, **N time parameter of type T**)
: data(**vector will get N times type T**)
{
}

protected:
vector<T> data;

我應該如何實施它? 解決方案可能是在 c++11/14 中,我收到了一些錯誤,例如“參數包未使用 '...' 擴展”等。

此代碼示例可能有用:

#include <vector>
#include <utility>

template<typename T>
class MyClass {
public:
    template<typename ...Args>
    MyClass(int a, int b, Args&& ...args) :data{ std::forward<Args>(args)... } {}
private:
    std::vector<T> data;
};

int main() {
    MyClass<char> sample(1, 2, 'a', 'b');
    return 0;
}

[編輯]:添加了 std::forward,為實用程序添加了缺失的包含

假設 T 可以是任何東西,甚至是非常大或不可復制的東西,我們想要:

  1. 通過完美轉發保持效率。

  2. 檢查類型。

std::initializer_list滿足 2 但不滿足 1。

簡單的可變參數模板擴展滿足 1 而不是 2。

此解決方案使用可變參數模板擴展和enable_if來強制類型兼容性。

#include <vector>
#include <utility>
#include <string>


namespace detail
{
    constexpr bool all()
    {
        return true;
    }

    template<class...Rest>
    constexpr bool all(bool b, Rest...rest)
    {
        return b and all(rest...);
    };

}


template<class T>
class A
{
public:
    using value_type = T;  // say

    template<class...Rest,
            std::enable_if_t<detail::all(std::is_convertible<Rest, value_type>::value...)>* = nullptr>
    A(int a, int b, Rest&&...rest)
            : a_(a), b_(b)
    {
        this->fill(std::forward_as_tuple(std::forward<Rest>(rest)...),
                   std::make_index_sequence<sizeof...(Rest)>());
    }

private:
    template<class Tuple, std::size_t...Is>
    void fill(Tuple&& t, std::index_sequence<Is...> seq)
    {
        data_.reserve(seq.size());
        using expand = int[];
        void(expand{ 0,
                     (data_.push_back(std::move(std::get<Is>(t))), 0)...
        });
    }
private:
    int a_, b_;
    std::vector<value_type> data_;
};


int main()
{
    using namespace std::literals;

    auto a = A<double>(1, 2, 4.3, 5.5, 6.6);

    auto b = A<std::string>(1, 2, "the", "cat"s, "sat on the mat");

    // error: no matching constructor...
//    auto err = A<std::string>(1, 2, "the", "cat"s, 0.1);

}

干得好:

#include <iostream>
#include <vector>

template<class T>
struct V
{
    V(int n, std::initializer_list<T> l)
        : data(l)
    {
        (void) n;
    }

    std::vector<T> data;
};

int main()
{
    V<int> v(0,{1,2,3});
}

這不是一個完美的例子,因為需要用奇怪的語法(n, {optional, arguments, of, same, type})構造一個對象,但它確實提供了想要的行為。

下面的例子類似於 fr3nzy90 的,但隨着即將到來的 C++17,它將允許從構造函數參數中自動推導出T

template <class T>
class MyContainer {
    private:
    std::vector<T> data;

    public:
    // Take the first T value explicitly so it can be used to deduce
    // T from the constructor arguments (C++17 feature).
    template <class... Ts>
    MyContainer(int a, int b, T const & tval, Ts const &... tvals) :
      data{tval, tvals...} {
        …
    }

    // Special case, empty list, no implicit type deduction, because
    // there is no T value to deduce it from.
    MyContainer(int a, int b) {
        …
    }
};

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM