Use SFINAE but do not create a compiler error
source link: https://www.codesd.com/item/use-sfinae-but-do-not-create-a-compiler-error.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
Use SFINAE but do not create a compiler error
My program generates random strings that have a "type" and an identifier. Like so:
float lHTY8Au8b9 = float();
int dO3PNUInH6 = int();
float B_MtShimak = float();
float hgi_TzaVEv = float();
double mfW8kr6h6q = double();
std::string lSLj9antfj = std::string();
char MQkeARWYTL = char();
char Oe7G_ZRJy6 = char();
float qUwmOWeilK = float();
double FJYIODwQfx = double();
Then I have the following to see if two arbitrary variables can be added:
template <typename A, typename B>
typename std::enable_if<std::is_convertible<A, B>::value, decltype(A() + B())>::type
try_to_add(A a, B b) {
return a + b;
}
Of course, it works because I get the following error:
main.cpp:51:54: error: no matching function for call to ‘try_to_add(double&, std::string&)’
try_to_add<double,std::string>(mfW8kr6h6q,lSLj9antfj);
However what I want instead is a list of candidates that don't cause a compile error. I can't hardcode the template parameters because it only accepts ints, and I cannot check inside the generator program because they're just strings, and attempting to use try_to_add
with non-convertible types will cause a compile error. I know that SFINAE is the wrong approach, but is there a way to get try_to_add
to simply do nothing, rather than generate a compile error?
Add another overlaod with the inverse condition that does nothing.
template <typename A, typename B>
typename std::enable_if<!std::is_convertible<A, B>::value>::type
try_to_add(A, B) { }
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK