Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ template question

Tags:

c++

templates

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
}
like image 996
Yippie-Ki-Yay Avatar asked Jul 14 '10 10:07

Yippie-Ki-Yay


4 Answers

Just specialize for void:

template <typename T> struct Functional {
   T operator()() const {
      T a(5);
      return a;
   }
};
template <> struct Functional<void> {
   void operator()() const {
   }
};
like image 196
David Rodríguez - dribeas Avatar answered Nov 01 '22 20:11

David Rodríguez - dribeas


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);
}
like image 21
Johannes Schaub - litb Avatar answered Nov 01 '22 20:11

Johannes Schaub - litb


you could use a specialization


template &lt> struct Functional<void> {

   void operator()() const {
   }
};
like image 3
ULysses Avatar answered Nov 01 '22 19:11

ULysses


This should work

template <> struct Functional<void> //specialized for 'void'
{
   void operator()() const {

       //do something

      return ; //optional
   }
};

EDIT:

You can also write (Simpler approach)

T operator()() const {

   return T(5); // static_cast<> not even required
}
like image 1
Prasoon Saurav Avatar answered Nov 01 '22 20:11

Prasoon Saurav