Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
213 views
in Technique[技术] by (71.8m points)

Using templates on Container type in C++

I am trying to write a generic function to compute barycenter of a bunch of numbers, I found the following one but I am unable to use it:

template <typename Container>
auto getBarycenter(Container &&cont)
{
    decltype(cont[0]) res(0.0f);
    for (auto &v : cont)
        res += v;
    return res / static_cast<float>(cont.size());
}

I am new to templates, the data structure I am trying to operate on is std::vector < cv::Point3f > (from the OpenCV namespace).

EDIT:

Here is the calls I tried:

std::vector<float> vector;

auto value = vector.getBarycenter<std::vector>();
auto value = vector.getBarycenter<std::vector <cv::Point3f> >();
question from:https://stackoverflow.com/questions/65899232/using-templates-on-container-type-in-c

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Given the information you provided, there's at least one problem in that snippet showed.

decltype(cont[0]) evaluates to (potentially non-const) lvalue reference to the containers values. This can be fixed using std::decay_t (or std::remove_cvref, if you have access to c++20) which will remove the "reference-ness" and constness from the type.

template <typename Container>
auto getBarycenter(Container &&cont)
{
    std::decay_t<decltype(cont[0])> res(0.0f);
    for (auto &v : cont)
        res += v;
    return res / static_cast<float>(cont.size());
}

Alternatively, as mentioned by @Remy Lebeau you can use value_type if you're using std containers:

typename std::decay_t<Container>::value_type res(0.0f);

Also you should probably better default initialize res rather than use a float literal.

Live example here.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...