C++ 11 conditional template alias to function

130 views Asked by At

In C++ 11, I want to make a template alias with two specializations that resolve to a different function each.

void functionA();
void functionB();

template<typename T = char>
using Loc_snprintf = functionA;

template<>
using Loc_snprintf<wchar_t> = functionB;

So I can call e.g. Loc_snprintf<>() and it's resolve to functionA().

Apparently seems impossible (to compile). Is there something ultimately simple that mimics it (maybe using a class template)?

2

There are 2 answers

0
Some programmer dude On BEST ANSWER

In C++11 it's not really possible to create aliases of specializations. You must create actual specializations:

template<typename T = char>
void Loc_snprintf()
{
    functionA();
}

template<>
void Loc_snprintf<wchar_t>()
{
    functionB();
}

With C++14 it would be possible to use variable templates to create a kind of alias.

0
463035818_is_not_an_ai On

As others have already mentioned using is for types and unfortunately variable templates are only available in C++14.

Something that is perhaps closest to your initial approach using specialization is using a class template to store a function pointer to one of the two functions:

void functionA();
void functionB();

template <typename T = char>
struct Loc_snprintf {
    static constexpr void(*call)(void) = functionA;
};

template <>
struct Loc_snprintf<char> {
    static constexpr void(*call)(void) = functionB;
};