Ad
Disable Code From Compiling For Non Integral Types
#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
Related Questions
- → Comparing two large files are taking over four hours
- → Setting JSON node name to variable value
- → Compiling GLUT using Emscripten
- → Evaluate check box from a scanned image in node.js
- → Find an easy web server framework for mobile game
- → my https C++ code doesn't work on some sites (binance)
- → Error while opening pivx wallet on ubuntu
- → Why sending a POST by AJAX is interpreted by the HTTP Server as OPTIONS and sending by CURL is effectively a PUT?
- → Python reading in one line multiple types for a calculator
- → How do I properly pass an argument to a function
- → Accessing Websql database with Qt
- → Using Mysql C API for c++ codes
- → How do I set constants at run-time in a c++ header file, imported through Cython?
Ad