简体   繁体   English

专门用于联合类型的C ++模板方法

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

Suppose I have a union: 假设我有一个工会:

union U{
    int i;
    float f;
};

I want to write a generic method that uses it as a float or int. 我想编写一个将其用作float或int的通用方法。 Something like this: 像这样:

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;
}

Is there a way to do this? 有没有办法做到这一点? This was just an example method. 这只是一个示例方法。 I have a much longer, complicated method, and I don't want to duplicate it just to switch which union type it is using. 我有一个更长,更复杂的方法,我不想复制它只是为了切换它使用的是哪种联合类型。

Specialization would work: 专业化将起作用:

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; }

Usage: 用法:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM