C++模板问题

Yip*_*Yay 10 c++ templates

有没有办法实现指定的行为?如果有一些技巧或者可以使用特征来完成enable_if,请告诉我.

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
}
Run Code Online (Sandbox Code Playgroud)

Dav*_*eas 24

只是专注于虚空:

template <typename T> struct Functional {
   T operator()() const {
      T a(5);
      return a;
   }
};
template <> struct Functional<void> {
   void operator()() const {
   }
};
Run Code Online (Sandbox Code Playgroud)


Joh*_*itb 10

只需说以下内容即可.它非常适合T存在void并且相当于您显示的代码

T operator()() const {
  return static_cast<T>(5);
}
Run Code Online (Sandbox Code Playgroud)

  • +1:我不认为大多数人都知道你可以从返回类型为`void`的函数中"返回"一个类型为`void`的表达式. (3认同)