jeudi 7 septembre 2017

How complier finds template best match and evaluates expressions

My question is naive but help me out to understand if my reasoning it's correct. Here's the code I develop after watching part of a video conference of Walter E. Brown about metaprogramming. The code works. My question is more about how the compiler matches and evaluates the expressions.

//1 - Matches "simple" type. 
template <typename T_>  
struct mySizeof
{
    static constexpr size_t size = sizeof(T_);
};

//2 - Matches arrays of type T_ and size N.
template <typename T_,size_t N> 
struct mySizeof<T_[N]>
{
    //3 - What is T_ at this point??? 
    static constexpr size_t size = N * mSize<T_>::size;     
};

int main()
{
    using int_t = int;
    using int_arr = int[10][50][100];

    std::cout << mySizeof<int_t>::size << ":" << sizeof(int_t) << std::endl;
    std::cout << mySizeof<int_arr>::size << ":" << sizeof(int_arr) << std::endl;

    return 0;
}

//Parsing & evaluating int [10][50][100]
// 1.1 - Matches T_ = int[10][50][100]. But there's a better match.
// 1.2 - Better match. T_ = int, N = 10.
// 1.3 - Since [10] was consumed, lets check the remain expression. T_ becomes [50][100]. ???
// 2.1 - Matches T_ = int[50][100]. There's a better match.
// 2.2 - Better match. T_ = int, N = 50. 
//....
// 4.1 - It matches. T_ -> int
// 4.2 - Doesn't match.

I just need to understand at this point how compiler evaluates and finds out the best match, and how does it perform argument substitution.

Aucun commentaire:

Enregistrer un commentaire