[英]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.