The basic pattern for type selections based on a condition applied to the template parameters passed, or even independently looks like the following code demonstrates:
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 <typeinfo> | |
using namespace std; | |
template<typename FalseType, typename TrueType, bool condition> | |
struct ConditionalTypeSelector | |
{ | |
typedef void ResultType; | |
}; | |
template<typename FalseType, typename TrueType> | |
struct ConditionalTypeSelector<FalseType,TrueType,false> | |
{ | |
typedef FalseType ResultType; | |
}; | |
template<typename FalseType, typename TrueType> | |
struct ConditionalTypeSelector<FalseType,TrueType,true> | |
{ | |
typedef TrueType ResultType; | |
}; | |
struct A { | |
unsigned char member; | |
}; | |
struct B { | |
int member; | |
}; | |
struct C { | |
long long member; | |
}; | |
int main() { | |
cout << typeid | |
( ConditionalTypeSelector | |
< A,B,(sizeof(A) > sizeof(B)) | |
>::ResultType | |
).name() << endl; | |
cout << typeid | |
( ConditionalTypeSelector | |
< A,B,(sizeof(B) > sizeof(A)) | |
>::ResultType | |
).name() << endl; | |
cout << typeid | |
( ConditionalTypeSelector | |
< A,C,(sizeof(A) > sizeof(C)) | |
>::ResultType | |
).name() << endl; | |
cout << typeid | |
( ConditionalTypeSelector | |
< C,B,true>::ResultType | |
).name() << endl; | |
cout << typeid | |
( ConditionalTypeSelector | |
< C,A,false>::ResultType | |
).name() << endl; | |
return 0; | |
} |
A compiled and running example of the above code can be found here.
Sorry to everyone seeing this in the original version (thanks for the upvotes though)! I have fixed the sample code to show as put up on the corresponding github gist.
ReplyDelete