conditional template based code execution c++ -
so have been battling time , first post here. wanted know, if passed in container forward container, defined in boost, how can write code in way further checks see if code either backinsertionsequence or frontinsertionsequence , executes depending on type is?
template <class sequentialcontainer> void myclass<sequentialcontainer>::saysomething() { boost_concept_assert((boost::forwardcontainer<sequentialcontainer>)); if (boost::backinsertionsequence<sequentialcontainer> == true) { //do } else { //say else } }
if did if
check have there, both branches have compiled regardless of fact 1 branch ever executed particular type. severely limits usefulness of simple if
- need construct such 1 of branches compiles.
there 2 common ways of doing this. tag dispatch:
template <class sequentialcontainer> void myclass<sequentialcontainer>::saysomething() { saysomething<sequentialcontainer>( is_back_insertion_sequence<sequentialcontainer>{} ); } template <class sequentialcontainer> void saysomething(std::true_type /* insertion sequence */ ) { ... } template <class sequentialcontainer> void saysomething(std::false_type /* not insertion sequence */ ) { ... }
and sfinae:
template <class sequentialcontainer> typename std::enable_if< is_back_insertion_sequence<sequentialcontainer>::value >::type saysomething() { /* insertion sequence */ } template <class sequentialcontainer> typename std::enable_if< !is_back_insertion_sequence<sequentialcontainer>::value >::type saysomething() { /* not insertion sequence */ }
there advantages , disadvantages both, if it's 1 flag you're checking - it's matter of opinion.
Comments
Post a Comment