1

I know how to write a if else by meta-programming like this:

    template<bool con, typename Then, typename Else>
    struct IF;
    
    template<typename Then, typename Else>
    struct IF<true, Then, Else> {
        typedef Then result;
    };
    
    template<typename Then, typename Else>
    struct IF<false, Then, Else> {
        typedef Else result;
    };
    
    template<int num1, int num2>
    struct Add {
        static const int value = num1 + num2;
    };
    
    template<int num1, int num2>
    struct Sub {
        static const int value = num1 - num2;
    };
    
    template<bool con, int num1, int num2>
    struct addSub {
        static const auto RES = IF<con, Add<num1, num2>, Sub<num1, num2>>::result::value;
    };
    
    cout << addSub<1==1, 10, 2>::RES << endl;

But I still have no idea how to write While loop like this, could someone give me a simple example?

Joe k
  • 23
  • 4
  • 1
    You can't write a loop directly, but you can use recursion. Do you know how to emulate a while loop using recursion? – Thomas Feb 22 '21 at 16:56
  • `std::index_sequence` is a good tool also. – Jarod42 Feb 22 '21 at 16:58
  • https://stackoverflow.com/questions/1032602/template-ing-a-for-loop-in-c Did you try typing your query in google? – KamilCuk Feb 22 '21 at 17:00
  • 1
    A while loop normally performs some work until a condition is done. Can you show you us how you would like to use this imaginary `While` object? – NathanOliver Feb 22 '21 at 17:01

0 Answers0