【问题标题】:C++ explicit return type template specialisationC++ 显式返回类型模板特化
【发布时间】:2014-12-23 22:35:25
【问题描述】:

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


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

【问题讨论】:

  • "上面的代码使用 gcc 4.8.3 编译并按预期工作" - 在 g++ 4.9.0 -std=c++11 中无法编译; template&lt;int N&gt; auto getOutputPort2(); 这行说它不能推断返回类型
  • @MattMcNabb 感谢您指出这一点。你试过-c++1y吗?对我来说,在这种情况下,它甚至不会发出警告......但是,我肯定希望确保代码至少可以与 gcc 4.8.3+ 一起使用。您还使用什么其他编译器选项?从 C++14 标准的角度来看,这段代码是否正确?我很遗憾没有在我的问题中包含此评论的最后一个问题...
  • 不知道很抱歉 - 也许发布一个新问题来询问它是否是有效的 C++14 !我使用 gcc.godbolt.org 上的在线编译器进行检查。

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


【解决方案1】:

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

【讨论】:

  • 我不知道,抱歉。新推导的返回类型语法有一些我还没有完全理解的微妙之处。
猜你喜欢
  • 1970-01-01
  • 2019-02-26
  • 1970-01-01
  • 1970-01-01
  • 2021-12-28
  • 1970-01-01
  • 2019-06-09
  • 1970-01-01
  • 2015-02-22
相关资源
最近更新 更多