(@enhzflep가 주석에서 지적했듯이).
그러나 실제로 그렇게해야하는 경우 컨테이너에 저장할 유형을 알고 있으면 템플릿을 사용하여 최종 알고리즘을 조합 할 수 있습니다. 즉,의 라인을 따라 뭔가 :
template<typename T>
unsigned get_size(const T& val) {
return compute_size<T>::of(val);
}
같은 것으로 선도 :
// for PODs we don't really have to iterate
template<>
struct compute_size<std::vector<int>> {
static unsigned of(const std::vector<int>& v) {
return sizeof(v) + v.capacity() * sizeof(int);
}
};
: 같은 몇 가지 가능한 최적화와
std::vector<std::string> qqq;
qqq.push_back("asdfasdf");
qqq.push_back("qwer");
std::cout << get_size(qqq) << std::endl;
함수 템플릿을 통해 사용
template<typename T>
struct compute_size {
static unsigned of(const T& t) {
assert(false && "not implemented");
return 0;
}
};
template<typename T>
struct compute_size<std::vector<T>> {
static unsigned of(const std::vector<T>& v) {
// static size
unsigned result = sizeof(std::vector<T>);
// static and dynamic size of all used elements
for(auto& i : v)
result += compute_size<T>::of(i);
// account for allocated empty space
result += (v.capacity() - v.size()) * sizeof(T);
return result;
}
};
template<>
struct compute_size<int> {
static unsigned of(const int&) {
return sizeof(int);
}
};
template<>
struct compute_size<std::string> {
static unsigned of(const std::string& s) {
return sizeof(std::string) + s.capacity() * sizeof(std::string::value_type);
}
};
그리고 아마도, std::enable_if
을 사용하여 이것을 전체 유형 그룹으로 일반화합니다.
정적 또는 동적 메모리? – soon
정적 및 동적 – Deepak
'sizeof (myVec)'는 요소의 크기를 가져올만큼 충분하지 않습니까? ??? – Xlander