Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

can i write a user defined deduction rule for array to vector?

Tags:

c++

arrays

vector

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'

like image 750
Klaus Ahrens Avatar asked Mar 03 '23 21:03

Klaus Ahrens


1 Answers

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);
like image 66
lubgr Avatar answered Apr 05 '23 23:04

lubgr