jeudi 21 novembre 2019

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;
};

Aucun commentaire:

Enregistrer un commentaire