0
constexpr bool IsPrime(size_t Tar)
{
    for(size_t i = 2;i< Tar/2;++i)
    {
        if(Tar %i ==0)
        {
            return false;
        }
    }
    return Tar > 1;
}


template<int Sz ,bool = IsPrime(Sz)>
struct Helper{
    int value = 1;
};

template<int Sz>
struct Helper<Sz,false>{
    int value = 2;
};

template<int Sz>
struct Helper<Sz,true>{
    int value = 3;
};

int main(int argc, char** argv)
{
   Helper<2> h1;
   Helper<9> h2;
   std::cout<<h1.value<<std::endl;
   std::cout<<h2.value<<std::endl;
}

IsPrime(Sz) It is the default value of the main template parameter. Why does the calculated result finally match the template Helper<Sz, false>/Helper<Sz, true>. Is it because the editor matches a more specific template after getting the template parameters

  • Yes I think it checks if there are any available specializations and if any matching specialization is found, it uses that. – kiner_shah Sep 15 '22 at 06:33
  • This is exactly why specializations are used. This is explained in any [good c++ book](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list) – Jason Sep 15 '22 at 06:34

0 Answers0