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

Mae*_*tro 1 c++ 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
}
Run Code Online (Sandbox Code Playgroud)
  • Please help. I don't know how to implement it.

Jar*_*d42 5

您需要提供第二个参数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;
}
Run Code Online (Sandbox Code Playgroud)