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

C++ template function explicit specialization with multiple template types

I’d like to write a templatized function with two template types: one a bool and one a typename, and I’d like to specialize on the typename.

eg, this is what I want, but specialized on just a couple types for T:

template<bool b, typename T>
void foo(T val)
{
   // do different stuff based on b and type of T.
}

without the bool in there, I can do something like this:

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

template<typename T>
void bar(T val) {
    static_assert(false, "not implemented");
}

template<>
void bar<short>(short val) {
    printf("it's a short!\n");
}

I can’t figure out the syntax for this, and the microsoft docs on specialization only cover the single-type case.

>Solution :

template<bool B, typename T>
void foo(T const&)
{
    static_assert(false, "not implemented");
}

template<bool B>
void foo(short)
{
    printf("it's a short!\n");
}

However, this is not really specialisation, but overloading, which is completely appropriate. In fact, you could omit the general case.

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