当重载方法时,我相信编译器会在多个匹配项可用时选择更简单的匹配项。
考虑这段代码:
#include <iostream>
#include <string>
struct A {
static void foo(const char *str) {
std::cout << "1: " << str << std::endl;
}
template<int N> static void foo(const char (&str)[N]) {
std::cout << "2: " << str << std::endl;
}
};
int main()
{
A::foo("hello");
}
输出是1: hello
。然而,如果我注释掉 static void foo(const char *str)
方法,它会正常编译并输出 2: hello
。
我怎样才能在一个类上同时使用这两种方法,以便已知大小的数组将调用模板方法,而指针类型将调用非模板方法?
我尝试了以下方法:
struct A {
template<class _Ty = char>
static void foo(const _Ty *str) {
std::cout << "1: " << str << std::endl;
}
template<int N> static void foo(const char (&str)[N]) {
std::cout << "2: " << str << std::endl;
}
};
但是 g++ 给我以下错误:
In function 'int main()':
17:17: error: call of overloaded 'foo(const char [6])' is ambiguous
17:17: note: candidates are:
6:15: note: static void A::foo(const _Ty*) [with _Ty = char]
10:32: note: static void A::foo(const char (&)[N]) [with int N = 6]
最佳答案
正如 T.C. 所建议的,这是有效的:
struct A {
template<class T, typename = typename std::enable_if<std::is_same<T, char>::value>::type>
static void foo(const T * const & str) {
std::cout << "1: " << str << std::endl;
}
template<int N> static void foo(const char (&str)[N]) {
std::cout << "2: " << str << std::endl;
}
};
int main()
{
A::foo("hello1");
const char *c = "hello2";
A::foo(c);
char *c2 = new char[7];
::strcpy(c2, "hello3");
A::foo(c2);
// does not compile
// int *c3;
// A::foo(c3);
}
输出:
2: hello1
1: hello2
1: hello3
我希望我不必模板化指针方法,因为它为误用意外类型打开了大门,但我可以接受这个解决方案。
关于c++ - 优先使用带有大小模板的方法而不是带有指针类型的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40777473/