gpt4 book ai didi

c++ - 你可以使用关键字显式来防止方法参数的自动转换吗?

转载 作者:IT老高 更新时间:2023-10-28 14:00:01 26 4
gpt4 key购买 nike

我知道您可以对类的构造函数使用 C++ 关键字“显式”来防止类型的自动转换。你能用同样的命令来防止类方法的参数转换吗?

我有两个类(class)成员,一个以 bool 作为参数,另一个是 unsigned int。当我用 int 调用函数时,编译器将 param 转换为 bool 并调用了错误的方法。我知道最终我会替换 bool,但现在不想在开发这个新例程时破坏其他例程。

最佳答案

不,您不能使用显式,但您可以使用模板函数来捕获不正确的参数类型。

使用C++11,您可以将模板化函数声明为deleted。这是一个简单的例子:

#include <iostream>

struct Thing {
void Foo(int value) {
std::cout << "Foo: value" << std::endl;
}

template <typename T>
void Foo(T value) = delete;
};

如果您尝试使用 size_t 参数调用 Thing::Foo,则会出现以下错误消息:

error: use of deleted function
‘void Thing::Foo(T) [with T = long unsigned int]’

pre-C++11代码中,可以改用未定义的私有(private)函数来完成。

class ClassThatOnlyTakesBoolsAndUIntsAsArguments
{
public:
// Assume definitions for these exist elsewhere
void Method(bool arg1);
void Method(unsigned int arg1);

// Below just an example showing how to do the same thing with more arguments
void MethodWithMoreParms(bool arg1, SomeType& arg2);
void MethodWithMoreParms(unsigned int arg1, SomeType& arg2);

private:
// You can leave these undefined
template<typename T>
void Method(T arg1);

// Below just an example showing how to do the same thing with more arguments
template<typename T>
void MethodWithMoreParms(T arg1, SomeType& arg2);
};

缺点是在这种情况下代码和错误消息不太清楚,因此应尽可能选择 C++11 选项。

对每个采用 boolunsigned int 的方法重复此模式。不要为方法的模板化版本提供实现。

这将强制用户始终显式调用 bool 或 unsigned int 版本。

任何使用 boolunsigned int 以外的类型调用 Method 的尝试都将编译失败,因为该成员是私有(private)的,受制于当然,可见性规则的标准异常(exception)( friend 、内部调用等)。如果有访问权限的东西调用了私有(private)方法,你会得到一个链接器错误。

关于c++ - 你可以使用关键字显式来防止方法参数的自动转换吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/175689/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com