C ++模板问题

时间:2010-07-14 10:14:00

标签: 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
}

5 个答案:

答案 0 :(得分:24)

专注于虚空:

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

答案 1 :(得分:10)

请说以下内容。它与T void完美匹配,相当于您显示的代码

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

答案 2 :(得分:3)

你可以使用专业化


template <> struct Functional<void> {

   void operator()() const {
   }
};

答案 3 :(得分:1)

这应该有效

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

       //do something

      return ; //optional
   }
};

编辑:

你也可以写(更简单的方法)

T operator()() const {

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

答案 4 :(得分:0)

此代码存在比首次出现更大的问题。例如,如果你要将Functional的返回值转发给另一个函数,那么你不能只将函数声明为void - 整个批次必须被指定为void,因为如果你有一个无效的函数,你可以传递给它一个无效的表达。当然,你不能用void等创建变量。总的来说,更容易说虚空是非法的,而不是试图处理它。

还有其他答案已经有明确的专业化答案。