簡體   English   中英

具有模板成員的模板類的模板類型推導

[英]Template type deduction of template class with template member

可以說我有下面的模板類(Bjarne Stroustrup的書中的例子令人困惑)

template<class Scalar> class complex {
    Scalar re, im;
public:
        template<class T>
        complex(const complex<T> &c) : re(c.re), im(c.im) {}
        //...
}
  1. complex<float> cf(0,0); 是創建此類對象的一種方法,但是在此示例中, Scalar推導為float還是T推導為float? 創建此類的對象有哪些不同的方法? 我想了解如何從這些示例中推斷出模板類型。
  2. 成員模板的用途是什么?

complex<float> cf(0,0); 是創建此類對象的一種方法,但是在此示例中, Scalar推導為float還是T推導為float 創建此類的對象有哪些不同的方法? 我想了解如何從這些示例中推斷出模板類型。

在此示例中,沒有任何推斷。 Scalar明確指定為float

模板構造函數不會為此被調用。

成員模板的用途是什么?

說您有:

Complex<float> c1(10, 20);

然后您要使用c1創建另一個ComplexScalar類型不同。

Complex<double> c2(c1);

在這種情況下,使用模板構造函數。 Scalar明確指定為doubleT推導為float

template<class Outer>
struct S1 {
    template<class Inner>
    S1(const S1<Outer>& rhs) {}
};

template<class Outer>
struct S2 {
    template<class Inner>
    S2(const S2<Inner>& rhs) {}
};

S1<float> s1f;
S2<float> s2f;

S1<double> s1d(s1f); // error
S2<double> s2d(s2f); // ok

演示的是從參數的模板類型中推導出成員函數模板參數。

對於上面的s2d ,我們知道Outer是double,未指定為推斷。

但是,當我們將s2f傳遞給它的構造函數時,我們傳遞的是S2類型的對象。 我們提供了一個采用S2<? Inner ?> S2<? Inner ?> ,因此如果推斷Inner為浮點型,則我們有一個容器匹配項。

正在演示的是帶有更多模板化成員函數的模板化類。 考慮:

template<class Outer>
struct S {
    template<class Other>
    S(const Other& rhs) {}
};

如果我們這樣做

S<float> sf;
S<int> si(sf);

在這里,復制構造函數推論Inner不僅是int而且是S<int>

實際使用:

template<class C, class T>
struct PtrContainer {
    using container_type = C;
    using value_type = T;
    using self_type = PtrContainer<container_type, value_type>;
    using ptr_type = T*;
    using size = sizeof(T);

    PtrContainer() : c() {}

    void append(ptr_type p) {
        c.push_back(p);
    }

    template<class D>
    std::enable_if<std::is_base_of<T, D>::value, void>::type
    transfer(PtrContainer<D>& rhs) {
        c.insert(c.end(), rhs.c.begin(), rhs.c.end());
        rhs.c.clear();
    }

    void clear() {
        for (auto* ptr: c) {
            delete ptr;
        }
        c.clear();
    }

    ~PtrContainer() { clear(); }

    container_type<ptr_type> c;
};

struct S {};
struct SD : public S {};

int main() {
    PtrContainer<vector, S> pvs;
    pvs.append(new S);
    PtrContainer<list, SD> plsd;
    plsd.append(new SD);
    pcs.transfer(plsd);
}

在您的示例中,代碼將Scalar明確指定為float (不進行扣除)。 但是您顯示的copy(ish)構造函數不是在后續示例中將被調用的構造函數。

暫無
暫無

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

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