jeudi 1 octobre 2015

Template function to return tuple values (different types) via ENUM lookup

the following code produces

"error: invalid operands of types '' and 'const size_t {aka const long unsigned int}' to binary 'operator<'" (gcc-4.9.1)

I just want a lookup function for default values of different types. Is this supposed to work at all?

#include <iostream>
#include <string>
#include <tuple>

// IDs
enum class ID : size_t
{
    AAA, // 0
    BBB, // 1
    CCC, // 2
    DDD  // 3
};

// default values for each ID
const auto defaultValsForIDs = std::make_tuple(
        int(1),             // 0
        std::string("bbb"), // 1 
        double(3.5),        // 2
        int(-5)             // 3
);


//------------------------------------------------------
// HERE IS WHERE IT GETS MESSY:
//------------------------------------------------------
// default values for each deviceID
template<typename EnumT>
using underlayingEnumT = typename std::underlying_type<EnumT>::type;

template<typename EnumT>
constexpr underlayingEnumT<EnumT> to_underlying(EnumT e) 
{
    return static_cast<underlayingEnumT<EnumT>>(e);
}

template<typename EnumT>
auto getDefaultValue(const EnumT e) 
-> decltype(std::get<to_underlying<EnumT>(e)>(defaultValsForIDs)) // <- THIS WON'T WORK
{
    return std::get<to_underlying<EnumT>(e)>(defaultValsForIDs);
}


//------------------------------------------------------
// THIS DOES NOT COMPILE AS WELL
//------------------------------------------------------
template<>
auto getDefaultValue(const size_t xx) 
-> decltype(std::get<xx>(defaultValsForIDs)) // <- THIS WON'T WORK
{
    return std::get<xx>(defaultValsForIDs);
}

int main(int , char** )
{
    std::cout << getDefaultValue(ID::AAA) << std::endl;

    return 0;
}

Am I missing a 'template' somewhere? see Where and why do I have to put the "template" and "typename" keywords? or Compile error: unresolved overloaded function type

Aucun commentaire:

Enregistrer un commentaire