Search code examples
c++sfinae

How to deactivate non-integral versions of my `Pow(T)` using SFINAE?


I am asked to use SFiNAE to reject non-integral versions of my Pow(T) template function. So if the type deduced is an integral then return argument * argument otherwise do nothing and just inform that the version has been rejected by SFINAE.

Here is my try:

template<typename T>
auto Pow(T x)->std::enable_if_t<std::is_integral<T>::value>
{
    return x * x;
}

void Pow(...)
{
    std::cout << "rejected by SFiNAE" << std::endl;
}


int main() 
{
    auto ret = Pow(5); // error here:  'ret': variable cannot have the type 'void'
    cout << typeid(Pow(5)).name() << endl; // void
}
  • Please help. I don't know how to implement it.

Solution

  • You need to provide the second parameter to std::enable_if:

    template<typename T>
    auto Pow(T x)->std::enable_if_t<std::is_integral<T>::value, decltype(x * x)>
    {
        return x * x;
    }