4
\$\begingroup\$

I just wrote this template to detect if a given element is found inside a container:

template <typename Iterator> bool is_contained(Iterator begin, Iterator end, decltype(*begin) object)
{
    for (; begin != end; ++begin)
    {
        if (*begin == object)
        {
            return true;
        }
    }
    return false;
}

Which then would be called for examples as:

bool test = is_contained<decltype(container.begin())>(container.begin(), container.end(), anything);

This works fine, but I believe it is not so readable. I am also new to using decltype which makes me wonder if this would crash, and somehow I wont be calling the template correctly. Any feedback is highly appreciated.

\$\endgroup\$
8
\$\begingroup\$

Note that for functions the compiler will detect the template types based on the parameters.
So you can simply write:

bool test = is_contained(container.begin(), container.end(), anything);

I don't particularly like the use of decltype in your function. I would simply make it another template parameter.

template <typename Iterator, typename Value>
bool is_contained(Iterator begin, Iterator end, Value const& object);

Because of the compiler deducing the names you can use any type. Also this is more flexable as it allows you to use any type that is comparable to the type inside the container (rather than only allowing values that are the same type (or trivial convertible)).

\$\endgroup\$
5
\$\begingroup\$
  1. Do you want to test whether an element is in a container, or an iterator-range?

    • The first allows for optimisation (taking advantage of the container's peculiarities). See "contains() algorithm for std::vector" for an example.
    • The second is more general in the absence of any range-library, like the one expected for the C++20 standard, and available for earlier versions.
  2. Constraining the needle to the type decltype(*begin) is very problematic:

    • It forces pass-by-value, which while it should be possible, at least with moveing, might be inefficient.
    • You cannot take advantage of transparent comparators (a C++14 feature), forcing the creation of a useless temporary. On the flip-side, if transparent comparators are not used, only a single temporary is constructed.
    • If the type is a proxy like with the dreaded std::vector <bool>, hilarity ensues.
  3. Consider taking advantage of the standard library, specifically std::find ().

  4. C++ will deduce the function's template-arguments perfectly fine, no need for error-prone verbosity.

\$\endgroup\$
  • \$\begingroup\$ On point 2, it's even worse: you can't pass a value that's convertible to decltype(*begin), because templates need exact matches. \$\endgroup\$ – Toby Speight Mar 28 at 22:09

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.