开发者

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 wan开发者_如何学JAVAt 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 <> struct Functional<void> {

   void operator()() const {
   }
};


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
}


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜