简体   繁体   English

是否允许占位符作为 function 模板返回类型?

[英]Is placeholder allowed as function template return type?

Consider the following template and it's specialisation:考虑以下模板及其专业化:

template<typename R>
R func() {
    return 0;
}

template<>
auto func() {
    std::cout << "Auto deduced" << std::endl;
    return 1;
}

I'm not sure if such a declaration is allowed, but when compiling it with Xcode, clang emits a weird error:我不确定这样的声明是否被允许,但是当用 Xcode 编译它时,clang 会发出一个奇怪的错误:

clang: error: unable to execute command: Segmentation fault: 11
clang: error: clang frontend command failed due to signal (use -v to see invocation)
Apple clang version 14.0.0 (clang-1400.0.29.202)
Target: x86_64-apple-macos12.3
Thread model: posix

Despite not being able to invoke the specialisation, MSVC compiles it just fine .尽管无法调用专业化,但 MSVC 编译得很好 Is such a specialisation allowed and if so, how it can be used?是否允许这样的专业化?如果允许,如何使用?

[dcl.spec.auto.general]/13 provides the following details: [dcl.spec.auto.general]/13提供了以下详细信息:

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.具有使用占位符类型的已声明返回类型的 function 或 function 模板的重新声明或特化也应使用该占位符,而不是推导类型。 Similarly, redeclarations or specializations of a function or function template with a declared return type that does not use a placeholder type shall not use a placeholder.类似地,具有不使用占位符类型的已声明返回类型的 function 或 function 模板的重新声明或特化不得使用占位符。

In other words, any function template that doesn't use placeholder return type (even if it's a template parameter) cannot be specialised with placeholder return type:换句话说,任何不使用占位符返回类型的 function 模板(即使它是模板参数)都不能专门用于占位符返回类型:

template<typename R>
R func() { return 0; }

template<>
int func() { return 1; } // OK

template<>
auto func() { return "str"; } // Error. Redeclaration

Similarly, any template that use placeholder return type can be specialised only with placeholder return type:类似地,任何使用占位符返回类型的模板都只能用占位符返回类型进行特化:

template<typename R>
auto func(R arg) { return arg; }

template<>
auto func(int arg) { return arg; } // OK

template<>
float func(float arg) { return arg; } // Error. Redeclaration

For clang it's a compiler bug, MSVC is just wrong to accept it and only GCC rejects it as expected :对于 clang,这是一个编译器错误,MSVC 接受它是错误的,只有GCC 按预期拒绝它

<source>:9:6: error: template-id 'func<>' for 'auto func()' does not match any template declaration
    9 | auto func() {
      |      ^~~~
<source>:4:3: note: candidate is: 'template<class R> R func()'
    4 | R func() {
      |   ^~~~
Compiler returned: 1

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM