我想使用枚举值作为索引来访问元组项。我已阅读这篇文章以提供帮助。
我在 VS2013 中工作,因此如果auto
没有trailing return
.
静态转换工作,但它很麻烦,而且它要求元组可以自由访问(在实际代码中,属性在protected
范围内)。
我想通过使用模板化方法来改进这一点GetAttribute
。
我试过了,但它产生了一个错误:
prog.cpp:30:119: 错误: '' 和 'size_t {aka unsigned int}' 类型的无效操作数到二进制 'operator<' auto GetAttribute(AttributeName attributeName) -> decltype(std::declval(std::get (attributeName)>(attributes))) ^ prog.cpp:30:119: 错误:''和'size_t {aka unsigned int}'类型的无效操作数到二进制'operator<' prog.cpp:在函数'int main ()': prog.cpp:57:4: 错误: 'struct X' 没有名为 'GetAttribute' 的成员 x.GetAttribute(XParameters::PARAMETER1); // 不编译。^
#include <tuple>
#include <cstddef>
#include <utility>
#include <iostream>
enum class XParameters : unsigned int
{
PARAMETER1, // int
PARAMETER2, // float
MAX,
};
enum class YParameters : unsigned int
{
PARAMETER3 = XParameters::MAX // std::string
};
using XTuple = std::tuple<int, float>;
using YAttributes = std::tuple<std::string>;
using YTuple = decltype(tuple_cat(XTuple(), YAttributes()));
template <typename Attributes>
struct Common
{
Common(Attributes&& attr) : attributes(std::move(attr)) {}
Attributes attributes;
template <typename AttributeName>
auto GetAttribute(AttributeName attributeName) -> decltype(std::declval(std::get<static_cast<size_t>(attributeName)>(attributes)))
{
return std::get<static_cast<size_t>(attributeName)>(attributes);
}
};
struct X : Common<XTuple>
{
X() : Common(std::make_tuple(42, 3.14f)) {}
};
struct Y : Common<YTuple>
{
Y() : Common(std::make_tuple(666, 0.01f, "string")) {}
};
int main()
{
X x;
Y y;
int parameter1 = std::get<static_cast<size_t>(XParameters::PARAMETER1)>(x.attributes); // Compiles, works.
std::cout << parameter1 << std::endl;
std::string parameter3 = std::get<static_cast<size_t>(YParameters::PARAMETER3)>(y.attributes); // Compiles, works.
std::cout << parameter3 << std::endl;
// Shorter code
x.GetAttribute(XParameters::PARAMETER1); // Does not compile.
//parameter3 = std::get<static_cast<size_t>(YParameters::PARAMETER3)>(x.attributes); // Does not compile, phew...
return 0;
}