Last active
May 18, 2020 12:43
-
-
Save gopi487krishna/6c738ed7b804e3ad0732aee84b6ad1b3 to your computer and use it in GitHub Desktop.
Implement is_convertible in C++
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
Task 4 : This is not an easy task and actually is a little complicated ( So it is going to be enjoyable ofcourse :) ) | |
* This task is going to check your knowledge on Overloading rules in C++, and concept of Template Meta Programming/ Compile Time | |
Programming | |
* The entire solution must strictly be compile time. | |
Your task is to define a type-trait ( see task 2 for an introduction to type trait ) called "is_convertible" which checks | |
whether the value/object of one type is convertible to other or not. | |
Examples : | |
Example 1 : is_convertible<int,float>::value should give "true" as int value can be converted to float value ( higher type ) | |
Example 2 : is_convertible<std::string,int>::value should give "false" as object of std::string cannot be converted to int | |
Hints : | |
1. Learn about overloading rules in C++ ( You have to really dig up ) | |
2. Learn about sizeof operator | |
3. Learn about std::type_traits | |
There is a standard type traits called std::is_convertible whose implementations you can refer from internet. | |
*/ | |
#include<iostream> | |
#include<string> | |
// Define this structure please ( Google type traits in C++ for some examples ) | |
template<typename T, typename U> | |
struct is_convertible{ | |
// MAKING IT A STRUCTURE IS COMPULSORY ( ALTHOUGH IF YOU ARE EXPERIENCED WITH TMP YOU CAN GO WITH ANY CHOICE ) | |
static constexpr bool value= /* Code that checks if T is convertible to U*/ | |
}; | |
int main(){ | |
// DO NOT EDIT MAIN | |
std::cout<<is_convertible<int,float>::value; // Should be true / 1 | |
std::cout<<is_convertible<std::string,int>::value; // Should be false / 0 | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment