这是修复模糊函数调用的正确方法吗?

时间:2016-09-12 12:52:41

标签: c++

我有这样的代码:

#include <cstdio>

void test(size_t const pos){
    printf("size_t\n");
}

void test(const void *ptr){
    printf("ptr\n");
}

//void test(int const pos){
//  printf("int\n");
//}

int main(){
    size_t x = 0;

    test(x);
    test(nullptr);
    test(&x);
//  test(0);
// some more that fail, but I do not care too much about them:
//  test(0U);
//  test(0L);
//  test(NULL);
}

当我取消注释test(0);时,它无法编译,因为编译器不知道如何转换'0'。

如果我引入'int'重载,一切都会再次编译。

这是避免模糊函数调用的正确方法吗?

更新

正确意味着 - 我不想调用指针重载,除非参数是指针或传递nullptr

我知道当前的“设置”因0U0LNULL而失败。

1 个答案:

答案 0 :(得分:4)

文字0的类型为int。如果存在test(int)重载,则会调用此方法,因为不需要转换。容易。

如果没有test(int)可用,则编译器将查看该参数是否可以转换为size_tvoid*以满足其他重载。文字0可以隐式转换为任一类型,转换规则不会告诉它更喜欢任何一种,因此结果不明确。

为了指定您要调用test(size_t),您需要明确创建0类型size_t,即

test(size_t{0});
相关问题