c++ - 优先使用带有大小模板的方法而不是带有指针类型的方法

标签 c++ arrays c++11 overloading c-strings

当重载方法时,我相信编译器会在多个匹配项可用时选择更简单的匹配项。

考虑这段代码:

#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/

相关文章:

c++ - 由于 DirectX,OpenCV 构建失败

C++ 输出格式错误

javascript - 集合大小和数组长度 - sonarqube

c++ - 从整型常量表达式转换为空指针

c++ - boost 不良词汇转换 : source type value could not be interpreted as target when converting a string to unsigned long long

c++ - win32 程序是否应该始终是多线程的

python - 二维数组python中的邻居

c# - 根据另一个数组中指定的索引从数组中选择元素c#

c++ - 是否允许类类型的 std::function 成员变量(不完整类型)?

c++ - 在 C++11 中使用 libuuid/uuid-dev