Created
November 4, 2023 19:59
-
-
Save mortymacs/7612a51cffbb758329c66bf6a298abf0 to your computer and use it in GitHub Desktop.
Sample std::enable-if 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
#include <iostream> | |
#include <string> | |
#include <type_traits> | |
// Custom data structures. | |
struct Car{ | |
std::string name; | |
}; | |
struct Bike{ | |
std::string name; | |
}; | |
struct Walk{ | |
std::string name; | |
}; | |
// Custom traits. | |
template <typename T> | |
struct IsVehicle { | |
static const bool value = false; | |
}; | |
template <> | |
struct IsVehicle<Car> { | |
static const bool value = true; | |
}; | |
template <> | |
struct IsVehicle<Bike> { | |
static const bool value = true; | |
}; | |
// Enable function if T is Car or Bike. | |
template <class T> | |
typename std::enable_if<IsVehicle<T>::value>::type Repair(T data_type) { | |
std::cout << "Repairing has started..." << data_type.name << std::endl; | |
} | |
int main() { | |
auto data_car = Car{name:"c1"}; | |
Repair(data_car); | |
auto data_bike = Bike{name:"b1"}; | |
Repair(data_bike); | |
// ERR | |
//auto data_walk = Walk{name:"w1"}; | |
//Repair(data_walk); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment