Last active
November 12, 2015 22:45
-
-
Save bfueldner/6ab1f8c1f930d9b12226 to your computer and use it in GitHub Desktop.
Template specialization
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> | |
#define FLOAT_VALIDATOR_ | |
template<typename T> | |
struct validator | |
{ | |
static const bool has_validator = false; | |
bool operator()(const T value) const | |
{ | |
return false; | |
} | |
}; | |
template<> | |
struct validator<int> | |
{ | |
static const bool has_validator = true; | |
bool operator()(const int value) const | |
{ | |
std::cout << "int validator" << std::endl; | |
return (value != 0); | |
} | |
}; | |
#ifdef FLOAT_VALIDATOR | |
template<> | |
struct validator<float> | |
{ | |
static const bool has_validator = true; | |
bool operator()(const float value) const | |
{ | |
std::cout << "float validator" << std::endl; | |
return (value != 0); | |
} | |
}; | |
#endif | |
template<typename T> | |
bool valid(const T value) | |
{ | |
static_assert(validator<T>::has_validator, "No validator"); | |
return validator<T>()(value); | |
} | |
int main(int argc, int *argv[]) | |
{ | |
int i = 5; | |
if (valid(i)) | |
{ | |
std::cout << "valid!" << std::endl; | |
} | |
float f = 5; | |
if (valid(f)) | |
{ | |
std::cout << "valid!" << std::endl; | |
} | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment