PaperTsar
PaperTsar

Reputation: 989

Template class with variable number of members in C++

This is more of a curiosity with C++ templates than something useful. It supposed to be a class with a variable number of members. Is it likely that this will be compiled down to direct member access?

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

Upvotes: 2

Views: 1878

Answers (1)

user6597796
user6597796

Reputation: 21

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

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

Upvotes: 2

Related Questions