gpt4 book ai didi

专门化 union 类型的 C++ 模板方法

转载 作者:行者123 更新时间:2023-11-27 23:54:13 27 4
gpt4 key购买 nike

假设我有一个 union :

union U{
int i;
float f;
};

我想编写一个将其用作 float 或整数的通用方法。像这样:

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

有没有办法做到这一点?这只是一个示例方法。我有一个更长、更复杂的方法,我不想为了切换它使用的 union 类型而复制它。

最佳答案

特化会起作用:

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

关于专门化 union 类型的 C++ 模板方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43857992/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com