Is there a way to use the container <T> :: size_type universally for different types of T?

Suppose I have a class with fields std::vector<bool> aand std::vector<int> bthat I want reserve()in the constructor to a size that is equal for both containers. Given that it reserve()takes a parameter size_typeto be completely safe, I need - from what I understand - to write my constructor using two parameters, which is not particularly attractive:

MyCtor(std::vector<bool>::size_type size1, std::vector<int>::size_type size2)
{
    abortIfNotEqual(size1, size2); // Proceed only if size1 == size2
    a.reserve(size1);
    b.reserve(size2);
}

From what I read, it size_typeusually matches size_t, at least for standard containers, so I could probably do this without encountering any potential problems:

MyCtor(std::size_t size)
{
    a.reserve(size); // More readable, but is this always ok?
    b.reserve(size);
}

size_type container<T> T?

container<T> , , , : a[i], i std::vector<bool>::size_type, , , , , unsigned int i .

, , ? size_t unsigned long int ?

+4
2

, , , , static_assert std:: is_same. ++ 17:

, size_type , , . , .

#include <vector>

class MyCtor {
    std::vector<bool> a;
    std::vector<int> b;
    typedef std::vector<bool>::size_type st1;
    typedef std::vector<int>::size_type st2;
    static_assert(std::is_same<st1, st2>::value);
public:
    typedef st2 size_type;
    MyCtor(size_type s1, size_type s2) {}
};

: , compiletime ( , Boost strong typedef), ++ 11.

+3

, . ++ 11 :

#include <vector>
#include <type_traits>
#include <limits>

typedef std::vector<bool>::size_type boolType;
typedef std::vector<int>::size_type intType;

typedef std::conditional<(std::numeric_limits<boolType>::max() <
                          std::numeric_limits<intType>::max()),
                         boolType,
                         intType>::type smallerSizeType;

MyCtor(smallerSizeType size)
{...}

++ 11, std::conditional std::numeric_limits<boolType>::max() static_cast<boolType>(-1) ..

+1

Source: https://habr.com/ru/post/1691505/


All Articles