is it possible to extend deduction rules in std?
#include <vector>
#include <array>
namespace std {
template< class T, size_t N >
vector(array<T, N>&) -> vector<T>;
}
int main() {
std::array a = {2,3,5,7}; // array<int, 4> !
std::vector w(a);
}
g++10.0 (wandbox) seems to ignore my version.
according to clang9.0 (Wandbox too) the predefined rule liv in a hidden space: error: deduction guide must be declared in the same scope as template 'std::__1::vector'
No, you are not allowed to do this. Putting stuff into namespace std
is allowed only in very rare cases, e.g. template specializations of std::hash
for example. In your case, you can use class template argument deduction with a little bit more typing than desired:
std::array a = {2,3,5,7};
std::vector w(a.cbegin(), a.cend());
Note that the parentheses are crucial for initializing w
, replacing them with braces deduces something quite different.
You can also factor the above constructor call out into a separate helper template:
template <class T, std::size_t N>
auto toVec(const std::array<T, N> a)
{
return std::vector(a.cbegin(), a.cend());
}
which allows for an initialization as
std::vector w = toVec(a);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With