Created
November 2, 2013 15:27
-
-
Save erikerlandson/7280097 to your computer and use it in GitHub Desktop.
Demo of using an 'invoke' shim with SFINAE and enable_if<> to conditionally specialize templates based on whether a given expression is defined for a parameter class type
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 <boost/utility/enable_if.hpp> | |
#include <boost/typeof/std/utility.hpp> | |
using boost::false_type; | |
using boost::true_type; | |
using boost::enable_if; | |
// always evaluates to true, as long as expression that generated 'X' compiled | |
template <typename X> struct invoke : public true_type {}; | |
// this default will always match, if nothing else does | |
template <typename X, typename Enabled=void> | |
struct dispatch { | |
static const int value = 37; | |
}; | |
// If the expression 'X().v' is defined, this specialization will match. | |
// otherwise, it will silently not match via SFINAE, with no compiler err | |
template <typename X> | |
struct dispatch<X, typename enable_if<invoke<BOOST_TYPEOF_TPL(X().v)> >::type> { | |
static const int value = 73; | |
}; | |
// define a test class having a member variable 'v' | |
struct ttt { | |
float v; | |
}; | |
int main(int argc, char** argv) { | |
std::cout << dispatch<ttt>::value << "\n"; // value is 73 | |
std::cout << dispatch<int>::value << "\n"; // value is 37 | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment