Medical physicist
Medical physicist

Reputation: 2594

Type casting in C++ with templates

In C++, is there any way to simplify the expression below using (for instance) templates?

std::stringstream data;
if (data_type == types::UINT8) {
    uint8_t val;
    data.read(reinterpret_cast<char*>(&val), sizeof(val));
    U.push_back(val);
} else if (data_type == types::UINT16) {
    uint16_t val;
    data.read(reinterpret_cast<char*>(&val), sizeof(val));
    U.push_back(val);
} else if (data_type == types::UINT32) {
    uint32_t val;
    data.read(reinterpret_cast<char*>(&val), sizeof(val));
    U.push_back(val);
} else if (data_type == types::UINT64) {
    uint64_t val;
    data.read(reinterpret_cast<char*>(&val), sizeof(val));
    U.push_back(val);
} else if (data_type == types::INT8) {
    int8_t val;
    data.read(reinterpret_cast<char*>(&val), sizeof(val));
    U.push_back(val);
} else if (data_type == types::INT16) {
    int16_t val;
    data.read(reinterpret_cast<char*>(&val), sizeof(val));
    U.push_back(val);
} else if (data_type == types::INT32) {
    int32_t val;
    data.read(reinterpret_cast<char*>(&val), sizeof(val));
    U.push_back(val);
} else if (data_type == types::INT64) {
    int64_t val;
    data.read(reinterpret_cast<char*>(&val), sizeof(val));
    U.push_back(val);
} else if (data_type == types::FLOAT64) {
    double val;
    data.read(reinterpret_cast<char*>(&val), sizeof(val));
    U.push_back(val);
} else {
    return false;
};

Upvotes: 0

Views: 72

Answers (1)

Anthony Williams
Anthony Williams

Reputation: 68561

Create a function template to do the read:

template<typename T>
void read(std::stringstream& data,TypeOfU& U){
  T val;
  data.read(reinterpret_cast<char*>(&val), sizeof(val));
  U.push_back(val);
}

Then use a switch:

switch(data_type){
case types::INT64: read<int64_t>(data,u); break;
case types::FLOAT64: read<double>(data,u); break;
// etc.
}

Upvotes: 5

Related Questions