0

这是对这个(更一般的)问题的跟进:previous 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在这里使用吗?


编辑。在下面的评论之后,我还想问一个额外的问题。从 C++14 标准的角度来看,上面的代码是否有效?如果不是,为什么不呢?

4

1 回答 1

2

您可以扩展帮助模板类的想法,并将几乎所有内容都放入其中。对于必须编写专业的人来说,这并不是很漂亮,但对于可以调用f<0>,f<1>等的用户来说非常方便。它并不真正需要 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(用更好的名字)完整。

于 2014-12-23T22:58:37.283 回答