Tutorial :C++ template question


Is there any way to achieve the specified behaviour? If there is some trick or this could be done using traits or enable_if, please let me know.

template <typename T> struct Functional {       T operator()() const {          T a(5);                    // I want this statement to be tranformed into                  // plain 'return;' in case T = void        return a; // <---     }  };    int main() {       Functional<int> a;     a();       Functional<void> b;     b(); // <--- Compilation error here  }  


Just specialize for void:

template <typename T> struct Functional {     T operator()() const {        T a(5);        return a;     }  };  template <> struct Functional<void> {     void operator()() const {     }  };  


Just say the following. It works perfectly well with T being void and is equivalent to the code you have shown

T operator()() const {    return static_cast<T>(5);  }  


you could use a specialization

  template &lt> struct Functional<void> {       void operator()() const {     }  };  


This should work

template <> struct Functional<void> //specialized for 'void'  {     void operator()() const {           //do something          return ; //optional     }  };  


You can also write (Simpler approach)

T operator()() const {       return T(5); // static_cast<> not even required  }  


There are bigger problems with this code than first appears. For example, if you were to forward the return value of Functional to another function, then you can't just spec Functional for void- the whole lot has to be specced for void, since if you have a function that takes void, you can't pass it a void expression. And of course, you can't create variables with void, and suchlike. Overall, it's just easier to say that void is illegal than try to deal with it.

There are other answers which already have the explicit specialization answer.

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Next Post »