Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why is this partial template specialization failing?

Here is my code.

#include <iostream>

template<class> struct IsInteger;
template<class> struct IsInteger { using value = std::false_type; };
template<> struct IsInteger<int> { using value = std::true_type; };

int main()
{
   std::cout << std::boolalpha << 
   IsInteger<5>::value::value << '\n';
}

Above code results in an error saying

Source.cpp(9,36): error C2974: 'IsInteger': invalid template argument for '<unnamed-symbol>', type expected

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Source.cpp(9,50): error C2955: 'IsInteger': use of class template requires template argument list

I don’t understand why the compiler doesn’t pick
template<> struct IsInteger<int> { using value = std::true_type; };
in this case. Why does it result in an error?

>Solution :

You need to use your trait as IsInteger<int> instead of IsInteger<5>.

Also, the idiomatic way to use std::true_type and std::false_type in cases like this is to inherit from them, instead of aliasing them as value:

template<class> struct IsInteger : std::false_type {};
template<> struct IsInteger<int> : std::true_type {};

int main()
{
   std::cout << std::boolalpha << IsInteger<int>::value << '\n';
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading