防止主要数据类型 C++ 的隐式转换

0 c++ implicit-conversion c++11 c++14 c++17

BLOT:C++ 具有隐式转换,我正在寻找一种方法来防止它。

让我举一个例子,下面的代码片段:

#include <iostream>

int incrementByOne(int i) {
    return ++i;
}

int main()
{
    bool b = true;
    
    std::cout << incrementByOne(b) << std::endl;

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

它将输出:2

我怎样才能防止这种隐式转换,并且即使在运行时也严格只采用 int 作为参数?

我能想到的一种方法是重载函数。所以新代码将如下所示:

#include <iostream>

int incrementByOne(int i) {
    return ++i;
}

int incrementByOne(bool) {
    std::cerr << "Please provide integer as argument" << std::endl;
    exit(0);
}

int incrementByOne(char) {
    std::cerr << "Please provide integer as argument" << std::endl;
    exit(0);
}

int main()
{
    bool b = true;
    
    std::cout << incrementByOne(b) << std::endl;

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

是否有其他(推荐)方法来防止运行时隐式转换?

Roh*_*ari 5

template<>您可以在和操作员的帮助下完成此操作delete

#include <iostream>

int incrementByOne(int x) {
    return ++x;
}

template<class T>
T incrementByOne(T) = delete; // deleting the function

int main(void) {
    std::cout << incrementByOne(-10) << std::endl;
    std::cout << incrementByOne('a') << std::endl; // will not compile

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

此后,传递给函数的参数必须是整数。

假设函数参数中给出了浮点值,您将收到错误:

main.cpp: In function 'int main()':
main.cpp:11:36: error: use of deleted function 'T incrementByOne(T) [with T = double]'
   11 |     std::cout << incrementByOne(3.5) << std::endl;
      |                                    ^
Run Code Online (Sandbox Code Playgroud)

  • 不错的代码。我不知道你可以这样使用“删除”。 (3认同)