簡體   English   中英

專門用於聯合類型的C ++模板方法

[英]C++ template method to specialize union types

假設我有一個工會:

union U{
    int i;
    float f;
};

我想編寫一個將其用作float或int的通用方法。 像這樣:

template <typename T>
T sum(std::vector<U> vec){
    T res(0);
    for (U &v: vec){
        res += ... // use v.i or v.f depending on what T is
    }
    return res;
}

有沒有辦法做到這一點? 這只是一個示例方法。 我有一個更長,更復雜的方法,我不想復制它只是為了切換它使用的是哪種聯合類型。

專業化將起作用:

template <typename T> T const & get(U const &);

template <> int const & get<int>(U const & u) { return u.i; }
template <> float const & get<float>(U const & u) { return u.f; }

用法:

for (U & v : vec) { res += get<T>(v); }

暫無
暫無

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

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