C ++中具有可变数量成员的模板类

时间:2016-07-16 13:49:48

标签: c++ templates c++11

这更像是对C ++模板的好奇而不是有用的东西。它应该是一个具有可变数量成员的类。是否可能将其编译为直接成员访问?

// type equality
template <typename X, typename Y> struct Eq { static const bool out = false; };
template <typename X> struct Eq<X, X> { static const bool out = true; };

template <typename First, typename... Rest>
class Table {
    First _field;
    Table<Rest...> _nextTable;
public:
    template <typename T>
    T &get() {
        if (Eq<First, T>::out)
            return (T&)_field;

        return (T&)_nextTable.get<T>();
    }
};

template<typename First>
class Table<First> {
    First _field;
public:
    template <typename T>
    T &get() {
        return _field;
    }
};

int main() {
    Table<int, double> table;
    table.get<double>() = 11.1;
}

1 个答案:

答案 0 :(得分:1)

return (T&)_nextTable.template get<T>();

http://en.cppreference.com/w/cpp/language/dependent_name