[英]How to pass a std::array to a function template which can accept std::vector
I'm trying to write a template, which can accept some sequence containers:我正在尝试编写一个模板,它可以接受一些序列容器:
template <typename S,
typename = std::enable_if_t<
std::is_same<S, std::array<typename S::value_type>, S::size()>::value ||
std::is_same<S, std::vector<typename S::value_type>>::value>>
std::string arr2String(const S& seqContainer) {
std::stringstream res;
for (const auto& element : seqContainer) {
res << element << "|";
}
return res.str();
}
However, this can't be compiled because of S::size()
.但是,由于
S::size()
无法编译。 Obviously, there is no such a thing.显然,没有这样的事情。
Is it possible to make such a template function, which can handle std::vector
and std::array
?是否可以制作这样一个模板 function,它可以处理
std::vector
和std::array
?
If you want to restrict your template to work for only std::array
or std::vector
, you can write some helper traits如果您想限制您的模板仅适用于
std::array
或std::vector
,您可以编写一些辅助特征
template <typename>
struct is_array : std::false_type {}
template <typename T, std::size_t N>
struct is_array<std::array<T, N>> : std::true_type {}
template <typename>
struct is_vector : std::false_type {}
template <typename... Ts>
struct is_vector<std::vector<Ts...>> : std::true_type {}
template <typename S,
typename = std::enable_if_t<
is_array<S>::value ||
is_vector<S>::value>>
std::string arr2String(const S& seqContainer) {
std::stringstream res;
for (const auto& element : seqContainer) {
res << element << "|";
}
return res.str();
}
Otherwise you can SFINAE on something more general否则你可以在更一般的东西上进行 SFINAE
template <typename S, typename = typename S::value_type>
std::string arr2String(const S& seqContainer) {
std::stringstream res;
for (const auto& element : seqContainer) {
res << element << "|";
}
return res.str();
}
Your code could in fact be compiled if you instantiated an array and took its size, which is constexpr.如果您实例化一个数组并获取它的大小(即 constexpr),您的代码实际上可以被编译。
template <typename S,
typename = std::enable_if_t<
std::is_same<S, std::array<typename S::value_type, S{}.size()>>::value ||
std::is_same<S, std::vector<typename S::value_type>>::value>>
std::string arr2String(const S& seqContainer) {
std::stringstream res;
for (const auto& element : seqContainer) {
res << element << "|";
}
return res.str();
}
This of course would be problematic if default initialization of your value type is expensive.如果值类型的默认初始化很昂贵,这当然会出现问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.