Template Functions: How to Use on Conditions

Laurie Stearn 91 Reputation points
2021-01-01T01:57:53.243+00:00

Hi there,
The body of the question is at the Site Feedback thread.
https://learn.microsoft.com/en-us/answers/idea/215631/cannot-post-question-attack.html
Will anyone be able to help?
Thanks.

C++
C++
A high-level, general-purpose programming language, created as an extension of the C programming language, that has object-oriented, generic, and functional features in addition to facilities for low-level memory manipulation.
3,757 questions
0 comments No comments
{count} votes

Accepted answer
  1. Barrnet Zhou-MSFT 171 Reputation points
    2021-01-01T06:44:44.663+00:00

    This code expression<int, opAndNot> exp(f(a), g(b), opAndNot()); calls the return value of the function. So, the T& a; T& b; should be modified to T a; T b;.

    Also, The reason for C2228 is just because the operand .exp to the left of the period (.) is not a class, structure, or union. You could put it in if or else.

    if (condA)
             expression<int, opAndNot> exp(f(a), g(b), opAndNot());
             int retVal = exp.eval();
    
    else
             expression<int, opOr> exp(f(a), g(b), opOr());
    
    1 person found this answer helpful.
    0 comments No comments

1 additional answer

Sort by: Most helpful
  1. Igor Tandetnik 1,106 Reputation points
    2021-01-01T06:23:03.48+00:00

    That seems unnecessarily complicated. How about something along these lines:

    auto conditionalOp = [](bool useOr, auto a, auto b) {
      return useOr ? (a | b) : (a & ~b);
    };
    result = conditionalOp(condA, f(a), g(b));
    result = conditionalOp(!condB, f(c), g(d));
    
    1 person found this answer helpful.

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.