开发者

Passing std::vector for any type to a function

开发者 https://www.devze.com 2022-12-09 13:55 出处:网络
Given: template<typename T> class A { B b; std::vector<T> vec1; std::vector<T> vec2; } I\'d like B to have a member function that fill() that takes a reference to those to vectors

Given:

template<typename T> class A {  
  B b;
  std::vector<T> vec1;
  std::vector<T> vec2;
}

I'd like B to have a member function that fill() that takes a reference to those to vectors and fills vec2 with values of T depending on some information contained in b.

One way of doing this is overloading fill() for each possible argument T:

fill(const std::ve开发者_JS百科ctor<float>& a, std::vector<float>& b)

and so on but this will mean a lot of unnecessary duplication as the operations are the same for every possible T. Inside of fill() I could use vector::value_type for the calculations but I don't know how to declare it in such a way that it takes every kind of std::vector. The obvious way would be to use a free function with templates. Is there a simpler way of doing this?


Templatize B.

template<typename T> class B {
  void fill(const std::vector<T>& a, std::vector<T>& b) { }
};

template<typename T> class A {  
  B<T> b;
  std::vector<T> vec1;
  std::vector<T> vec2;
}

If you don't want to templatize B, then templatize the fill function:

class B {
  template<typename T>
  void fill(const std::vector<T>& a, std::vector<T>& b) {}
};


You've gotten a number of answers, but I have to disagree with them, to at least some degree. My immediate reaction is that you shouldn't pass a vector to b::fill at all. Rather, you should pass an iterator (or maybe a pair of iterators). The rest is mostly right though: that still means fill should be a template member function. When you call it, you'll probably want to pass a std::back_insert_iterator, usually obtained with std::back_inserter.

Part of what you've said seems self-contradictory though: if b::fill modifies vec1 and vec2, they probably should not be passed as references to const. Admittedly, const doesn't have exactly its usual meaning when applied to a container, but the fact remains that passing a reference to const to a function whose sole intent is apparently to modify what's passed seems wrong.


Templatize fill:

class B {
public:
  template<typename T>
  void fill(const std::vector<T>& a, std::vector<T>& b)
  { /*...*/ }
  //...
};

(From your description it sees that b should be a const std::vector<T>&.)


You can define B as template class, fill as template function (inside a non-template class B) or, my favorite, use the standard std::transform/std::copy/std::fill, which are already template function, to populate your vector.
(All located inside <algorithm> header).

0

精彩评论

暂无评论...
验证码 换一张
取 消