简体   繁体   中英

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:

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 . Is such a specialisation allowed and if so, how it can be used?

[dcl.spec.auto.general]/13 provides the following details:

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. 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.

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:

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 :

<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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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