- Solution

In this lesson, we will look at the solution to using assertations to ensure that the algorithm only accepts natural numbers.

We'll cover the following...

Example

Press + to interact
// staticAssertGcd.cpp
#include <iostream>
#include <type_traits>
template<typename T>
T gcd(T a, T b){
static_assert(std::is_integral<T>::value, "T should be an integral type!");
if( b == 0 ){ return a; }
else{
return gcd(b, a % b);
}
}
int main(){
std::cout << std::endl;
std::cout << gcd(3.5, 4.0)<< std::endl; // should be gcd(3, 4)
std::cout << gcd("100", "10") << std::endl; // should be gcd(100, 10)
std::cout << std::endl;
}

Explanation

The static_assert operator and the predicate std::is_integral<T>::value enable us to check at compile time whether or not T is an ...