首页 文章

模板函数通过ENUM查找返回元组值(不同类型)

提问于
浏览
1

以下代码生成

“错误:类型''和'const size_t '的无效操作数到二进制'运算符<'”(gcc-4.9.1)

我只想要一个查找函数来获取不同类型的默认值 . 这应该适用吗?

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

我错过了 template 某个地方吗?见Where and why do I have to put the "template" and "typename" keywords?Compile error: unresolved overloaded function type

$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$
按照Piotr的建议编辑:

改变:

template<typename EnumT, EnumT e>
auto getDefaultValue() 
-> decltype(std::get<to_underlying<EnumT>(e)>(defaultValsForIDs))
{
    return std::get<to_underlying<EnumT>(e)>(defaultValsForIDs);
}

并为ID添加了实例:

template<ID id>
auto getDefaultValForID() 
-> decltype(getDefaultValue<ID, id>())
{
    return getDefaultValue<ID,id>();
}

然后:

int main()
{
    std::cout << getDefaultValForID<ID::BBB>() << std::endl;

    return 0;
}

奇迹般有效 .

1 回答

  • 3

    函数参数不是常量表达式,因此不能用作非类型模板参数 . 相反,您需要将其提升到模板参数列表:

    template <std::size_t xx>
    auto getDefaultValue() 
        -> decltype(std::get<xx>(defaultValsForIDs))
    {
        return std::get<xx>(defaultValsForIDs);
    }
    
    template <typename EnumT, EnumT e>
    auto getDefaultValue() 
        -> decltype(std::get<to_underlying<EnumT>(e)>(defaultValsForIDs))
    {
        return std::get<to_underlying<EnumT>(e)>(defaultValsForIDs);
    }
    

    然后使用它像:

    getDefaultValue<ID, ID::AAA>()
    

    要么

    getDefaultValue<0>()
    

    DEMO

相关问题