繁体   English   中英

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

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

考虑以下模板及其专业化:

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

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

我不确定这样的声明是否被允许,但是当用 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

尽管无法调用专业化,但 MSVC 编译得很好 是否允许这样的专业化?如果允许,如何使用?

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

具有使用占位符类型的已声明返回类型的 function 或 function 模板的重新声明或特化也应使用该占位符,而不是推导类型。 类似地,具有不使用占位符类型的已声明返回类型的 function 或 function 模板的重新声明或特化不得使用占位符。

换句话说,任何不使用占位符返回类型的 function 模板(即使它是模板参数)都不能专门用于占位符返回类型:

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

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

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

类似地,任何使用占位符返回类型的模板都只能用占位符返回类型进行特化:

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

对于 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