编译器如何找到模板最佳匹配和计算表达式

问题描述 投票:0回答:1

我的问题是幼稚的,但帮助我了解,如果我的推论是正确的。这里是看沃尔特·布朗E.约元编程视频会议的一部分后,我开发的代码。代码工作。我的问题是更多关于编译器如何匹配和评估表达式。

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

我只需要在这一点上编译器如何评估并找出最匹配的了解,以及它是如何执行参数替换。

c++11 templates template-meta-programming sfinae template-specialization
1个回答
2
投票

按照你的模式

解析和评价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, "!" );
 }
© www.soinside.com 2019 - 2024. All rights reserved.