C ++显式返回类型模板特化

时间:2014-12-23 22:35:26

标签: c++ templates c++11 overloading explicit-specialization

这是对此(更一般)问题的跟进:previous question。这里给出了对本问题的部分答案:partial answer to the present question

我对基于模板参数的返回类型的显式特化感兴趣。虽然上面给出的答案提供了解决问题的方法,但我相信使用C ++ 11/14技术可以更优雅地解决问题:

template<int N> auto getOutputPort2();
template<> auto getOutputPort2<0>();
template<> auto getOutputPort2<1>();

template<>
auto getOutputPort2<0>()
{
    return std::unique_ptr<int>(new int(10));
}

template<>
auto getOutputPort2<1>()
{
    return std::unique_ptr<string>(new string("asdf"));
}

上面的代码使用gcc 4.8.3编译并按预期工作(带-std = c ++ 0x标志)。但是,它会发出以下警告:

  

getOutputPort2函数使用auto类型说明符而不使用尾随返回类型。

根据我的理解,这将成为C ++ 14标准的一部分。但是,有没有办法在C ++ 11中实现上述功能?可以decltype在这里使用吗?


EDIT。根据以下评论,我还想问一个额外的问题。从C ++ 14标准的角度看,上面的代码是否有效?如果没有,为什么不呢?

1 个答案:

答案 0 :(得分:2)

您可以扩展帮助器模板类的概念,并将所有内容放在那里。对于那些必须编写专业知识的人来说,这并不完美,但对于能够拨打f<0>f<1>等的用户来说,它非常方便。它没有&#39 ;真的需要 decltype,但decltype确实让它更容易编写。

template <int N>
struct f_impl;

template <int N>
decltype(f_impl<N>::impl()) f()
{ return f_impl<N>::impl(); }

template <> struct f_impl<0> {
  static int impl() { return 1; }
};

template <> struct f_impl<1> {
  static const char *impl() { return " Hello, world!"; }
};

int main() {
  std::puts(f<1>() + f<0>());
}

您可以使用宏来管理它:而不是

template <> struct f_impl<1> {
  static const char *impl() { return " Hello, world!"; }
};

你可以写一些

的内容
#define DEFINE_F(N, Result)      \
  template <> struct f_impl<N> { \
    static Result impl();        \
  };                             \
  Result f_impl<N>::impl()

DEFINE_F(1, const char *) {
  return " Hello, world!";
}

但是我并不相信它只是完全写出f_impl(名字更好)的改进。

相关问题