gpt4 book ai didi

c++ - 在 C++14 中使用自动返回 'type' 进行显式模板特化是否有效?

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:24:13 25 4
gpt4 key购买 nike

Previous question .

我重复上一个问题的代码,使这个问题独立。如果使用 gcc 4.8.3 编译下面的代码,则它不会发出任何警告。使用 -std=c++1y。但是,如果使用 -std=c++0x 标志编译,它会发出警告。在上一个问题的上下文中,声明代码不使用 gcc 4.9.0 编译。不幸的是,目前我还没有完全理解 auto 是如何实现的。因此,如果有人能回答以下问题,我将不胜感激:

1).以下代码是否符合 C++14 标准的有效 C++?

2).如果是的话,这段代码会被认为是一种好的风格吗?如果不是,为什么不呢?

3).为什么下面的代码在使用 C++11 编译器时(有时)可以编译和工作?或者,为什么它并不总是有效?是否有任何特定的标志/选项/设置可以阻止它工作?

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("qwerty"));
}

最佳答案

1). Is the code below valid C++ with respect to the C++14 standard?

是的,据我所知。有时很难证明,因为通常没有什么可以禁止它。但是,我们可以看一下最近的草案(N4296 后)[dcl.spec.auto]/13 中的示例:

template <typename T> auto g(T t) { return t; } // #1
template auto g(int); // OK, return type is int
template char g(char); // error, no matching template
template<> auto g(double); // OK, forward declaration with
// unknown return type

同段规定:

Redeclarations or specializations of a function or function template with a declared return type that uses a placeholder type shall also use that placeholder, not a deduced type.

因此函数模板的显式特化必须使用返回类型推导。我找不到任何禁止不同特化的不同返回类型的内容。类似地,在 C++98 中,函数模板特化(相同主模板的)的不同返回类型可以通过使返回类型依赖于模板参数来实现。通过使用元编程,您基本上可以实现与使用返回类型推导为不同的特化指定不相关的返回类型时相同的效果。


3). Why does the code below seem to compile and work (sometimes) using C++11 compilers?

OP 中的代码在 C++11 中格式错误。普通函数(非 lamdas)的返回类型推导是 C++14 中引入的一个特性。包含此代码片段的程序格式错误。但是,该标准并未强制执行(编译器)必须拒绝格式错误的程序。它仅在 [intro.compliance]/2.2 中声明:

If a program contains a violation of any diagnosable rule [...] a conforming implementation shall issue at least one diagnostic message.

在/8

A conforming implementation may have extensions (including additional library functions), provided they do not alter the behavior of any well-formed program. Implementations are required to diagnose programs that use such extensions that are ill-formed according to this International Standard. Having done so, however, they can compile and execute such programs.

(因此实现可以接受此程序作为扩展。)

g++4.8.3 发出警告,算作诊断信息。 g++4.9 发出一个错误,这也是一条诊断信息。两者都是合规的。通过指定 -Werror,您可以告诉 g++4.8.3 拒绝该程序。 (您必须询问 gcc 开发人员,为什么他们将其从警告更改为错误。)

关于c++ - 在 C++14 中使用自动返回 'type' 进行显式模板特化是否有效?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27629816/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com