【问题标题】:Prevent implicit conversion for primary data types C++防止主要数据类型 C++ 的隐式转换
【发布时间】:2020-07-16 05:26:17
【问题描述】:

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

让我举一个同样的例子,对于下面的代码 sn-p:

#include <iostream>

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

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

    return 0;
}

它会输出: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;
}

还有其他(推荐的)方法可以防止运行时的隐式转换吗?

【问题讨论】:

标签: c++ c++11 c++14 c++17 implicit-conversion


【解决方案1】:

您可以在template&lt;&gt;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;
}

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

假设函数参数中给出了一个浮点值,你会得到错误:

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;
      |                                    ^

【讨论】:

  • 不错的代码。我不知道你可以这样使用delete
【解决方案2】:

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

如果传递的参数不是模板函数的integer,您可以static_assert。使用std::is_same检查类型。

#include <type_traits> // std::is_same

template<typename Type>
Type incrementByOne(Type x)
{
    static_assert(std::is_same<int, Type>::value, " Some valuable messages");
    return ++x;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-01
    • 1970-01-01
    • 1970-01-01
    • 2011-12-25
    • 1970-01-01
    相关资源
    最近更新 更多