zskalibur
zskalibur

Reputation: 41

I cannot understand some c++ template code

I am reading some codes but I cannot figure out how to understand the TH_convert<Elements>::t()....

  1. I have searched on google and found that ... can be used in variable numbers of arguments like printf(char **, ...). However, the following lines are different.

  2. I have seen that someone declared a member function as void test(...). Is that correct because the the function of variable arguments requires the first argument.

class TH_convert{
public:
    typedef std::tuple<Element> t;
};

template<typename... Elements>
class State{
public:
    typedef decltype(std::tuple_cat(typename TH_convert<Elements>::t()...)) t;
};

Upvotes: 0

Views: 95

Answers (1)

TartanLlama
TartanLlama

Reputation: 65770

I'll break it down piece-by-piece.

template<typename... Elements>
class State{
    //...
};

This defines a variadic class template called state which takes an arbitrary number of template parameters. State<int,bool> is a valid specialization of it, as is State<Foo,Bar,Baz,Qux> and even State<>.

decltype(/*...*/)

decltype is essentially replaced with the type of whatever expression you put in /*...*/.

typedef decltype(/*...*/) t;

This makes t a typedef for whatever the type of /*...*/ is.

typename TH_convert<T>::t()

This creates an object of type TH_convert<T>::t, which is the same as std::tuple<T>, given that definition of TH_convert. You need typename because it is a dependent type.

std::tuple_cat(typename TH_convert<Elements>::t()...)

This calls std::tuple_cat with typename TH_convert<T>::t() for every T in the parameter pack Elements. So for State<int,bool>, it is equivalent to:

std::tuple_cat(TH_convert<int>::t(), TH_convert<bool>::t())

For State<Foo,Bar,Baz,Qux> it's the same as:

std::tuple_cat(TH_convert<Foo>::t(), TH_convert<Bar>::t(),
               TH_convert<Baz>::t(), TH_convert<Qux>::t())

So, putting all that together:

typedef decltype(std::tuple_cat(typename TH_convert<Elements>::t()...)) t;

This makes t a typedef for the type of the result of std::tuple_catting together the result of TH_convert<T>::t() for each T in Elements.

Upvotes: 2

Related Questions