【发布时间】:2019-09-27 10:53:03
【问题描述】:
下面的函数test针对左值空字符串、左值非空字符串和右值字符串进行了重载。我尝试使用 Clang 和 GCC 进行编译,但在这两种情况下我都没有得到预期的结果。
#include <iostream>
void test(const char (&)[1]){ std::cout << __PRETTY_FUNCTION__ << std::endl; }
template <unsigned long int N>
void test(const char (&)[N]){ std::cout << __PRETTY_FUNCTION__ << std::endl; }
void test(char*&&){ std::cout << __PRETTY_FUNCTION__ << std::endl; }
int main(){
char str1[] = "";
char str2[] = "test";
test("");
test("test");
test(str1);
test(str2);
}
使用 clang 版本 6.0.0-1ubuntu2 输出:
clang++ test.cpp -o test.out && ./test.out
void test(const char (&)[1])
void test(const char (&)[N]) [N = 5]
void test(char *&&)
void test(char *&&)
使用 g++ 输出 (MinGW.org GCC-8.2.0-3):
g++ test.cpp -o test.exe && test.exe
test.cpp: In function 'int main()':
test.cpp:15:11: error: call of overloaded 'test(char [1])' is ambiguous
test(str1);
^
test.cpp:3:6: note: candidate: 'void test(const char (&)[1])'
void test(const char (&)[1]){ std::cout << __PRETTY_FUNCTION__ << std::endl; }
^~~~
test.cpp:6:6: note: candidate: 'void test(const char (&)[N]) [with long unsigned int N = 1]'
void test(const char (&)[N]){ std::cout << __PRETTY_FUNCTION__ << std::endl; }
^~~~
test.cpp:8:6: note: candidate: 'void test(char*&&)'
void test(char*&&){ std::cout << __PRETTY_FUNCTION__ << std::endl; }
^~~~
我的问题是:
- 哪个编译器是正确的?
- 对于 Clang,为什么
test(str1)和test(str2)选择右值重载,而它们是左值? - 使用 GCC,为什么调用
test(str1)不明确? - 这种情况有标准规则吗?
- 如何修复最后两个调用?
谢谢。
【问题讨论】:
标签: c++ language-lawyer overload-resolution value-categories