编译器如何找到模板最佳匹配并评估表达式

How compiler finds template best match and evaluates expressions

我的问题很幼稚,但请帮助我理解我的推理是否正确。这是我在观看了 Walter E. Brown 关于元编程的视频会议的一部分后开发的代码。该代码有效。我的问题更多是关于编译器如何匹配和评估表达式。

//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.

此时我只需要了解编译器如何评估和找出最佳匹配,以及它如何执行参数替换。

遵循您的架构

解析和评估int [10][50][100]

1.1 - 匹配 T_ = int[10][50][100]。但是有一个更好的匹配。 [右]

1.2 - 更好的匹配。 T_ = int, N = 10[错误:N=10, T_=int[50][100]]

1.3 - 由于 [10] 已消耗,让我们检查剩余表达式。 T_ 变为 [50][100]。 [T_ = int[50][100],见 1.2]

2.1 - 匹配 T_ = int[50][100]。有一个更好的比赛。 [右]

2.2 - 更好的匹配。 T_ = int, N = 50[错误:N=50 and T_=int[100]]

.....

4.1 - 匹配。 T_ -> int [右]

4.2 - 不匹配。 [右]

(p.s.: 如果我没记错的话,SFINAE 没有参与;只有专业化。)

一个简单的测试

#include <iostream>
#include <type_traits>

template <typename T>  
struct mySizeof
 { static constexpr std::size_t size { sizeof(T) }; };

template <typename T, std::size_t N> 
struct mySizeof<T[N]>
 {
   static constexpr size_t size { N * mySizeof<T>::size };     
   using type = T;
 };

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

   using T1 = typename mySizeof<T0>::type;
   using T2 = typename mySizeof<T1>::type;
   using T3 = typename mySizeof<T2>::type;

   static_assert( std::is_same<int[50][100], T1>::value, "!" );
   static_assert( std::is_same<int[100],     T2>::value, "!" );
   static_assert( std::is_same<int,          T3>::value, "!" );
 }