![](/img/trans.png)
[英]Is it valid to do explicit template specialisation with auto return 'type' in C++14?
[英]C++ explicit return type template specialisation
这是该(更一般的)问题的后续: 上一个问题 。 这里给出对当前问题的部分答案 : 对当前问题的部分答案 。
我对基于模板参数的返回类型的显式专业化感兴趣。 尽管以上给出的答案提供了解决问题的方法,但我相信,使用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标准的角度来看,以上代码是否有效? 如果没有,为什么不呢?
您可以扩展帮助程序模板类的概念,并将几乎所有内容放在其中。 对于必须编写专业知识的人来说,这不是很漂亮,但是对于用户来说非常方便,他们可以只调用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
(具有更好的名称)的改进。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.