Ad

Disable Code From Compiling For Non Integral Types

- 1 answer

#include <iostream>
#include <type_traits>
#include <math.h> 

template<typename T>
void Foo(T x)
{
    if(std::is_integral<T>::value)
    {
        rint(x);
    }
    else
    {
        std::cout<<"not integral"<<std::endl;
    }
}
int main()
{
    Foo("foo");
    return 0;
}

Does not compile because there is no suitable rint overload for const char*, but rint will never be invoked with const char* because it's not an integral type. How can I inform the compiler about this

Ad

Answer

In c++17 you could use if constexpr instead of if and it would work.

In c++14 you could specialize a struct to do what you want

template<class T, bool IsIntegral = std::is_integral<T>::value>
struct do_action
{
    void operator()(T val) { rint(val); }
};

template<class T>
struct do_action<T, false>
{
    void operator()(T val) { std::cout << "Not integral\n"; }
};

template<class T>
void Foo(T x)
{
    do_action<T>()(x);
}
Ad
source: stackoverflow.com
Ad