gpt4 book ai didi

c++ - 未命名的默认参数以防止歧义

转载 作者:太空宇宙 更新时间:2023-11-04 11:45:20 25 4
gpt4 key购买 nike

我有一个包含基于某些配置的(持久)相机集合的类。各种类与集合相关联,集合为实际实现提供各种接口(interface)。每个相机用户都以自己的方式与集合相关联(几乎可以认为它与自己的集合相关联,但实现可能会合并所有责任,例如:

#include <memory>
#include <map>

enum eCameraType{ eCameraType_IR, eCameraType_HDTV };
template <class CameraIF>
struct CameraCollectionIF
{
virtual CameraIF& camera( eCameraType, typename CameraIF::Tag = typename CameraIF::Tag() ) = 0;

protected:
~CameraCollectionIF(){}
};

struct CameraControlIF_A
{
struct Tag{};
virtual void doX() = 0;
};
struct CameraControllerA
{
void foo()
{
//Gets the camera in terms of responsibility associated with
// applicable control IF, but other classes can get camera (control) in
// terms of their responsibility, and that without ambiguity...
collection_->camera( eCameraType_HDTV ).doX();
}

std::shared_ptr<CameraCollectionIF<CameraControlIF_A>> collection_;
};

struct CameraControlIF_B
{
struct Tag{};
virtual void doY() = 0;
};
struct CameraControllerB
{
void foo()
{
//Gets the camera in terms of responsibility associated with
// applicable control IF, but other classes can get camera (control) in
// terms of their responsibility, and that without ambiguity...
collection_->camera( eCameraType_IR ).doY();
}

std::shared_ptr<CameraCollectionIF<CameraControlIF_B>> collection_;
};

//Now implementation of actual collection...

struct Camera : CameraControlIF_A, CameraControlIF_B
{
//etc...
};

struct CameraCollectionForConfigurtionX :
CameraCollectionIF<CameraControlIF_A>,
CameraCollectionIF<CameraControlIF_B>
{
private:
//Assume for now all camera types shall exist in map, therefore lookup can't
// fail...
virtual CameraControlIF_A& camera(
eCameraType cameraID, CameraControlIF_A::Tag ) override
{
return( *cameras_[cameraID] );
}
virtual CameraControlIF_B& camera(
eCameraType cameraID, CameraControlIF_B::Tag ) override
{
return( *cameras_[cameraID] );
}
//etc...
std::map<eCameraType, std::unique_ptr<Camera>> cameras_;
};

// Other configurations may exist that hold different collection of cameras....

上面提到的基本原理可以争论,但它确实提供了各种 Controller 及其摄像头之间的解耦,而与系统的配置方式无关。

我的问题是:

由于从不通过集合的公共(public)接口(interface)调用虚函数“camera”,我想人们不必将默认参数指定为与基类相同,事实上,省略是可以的它完全:

virtual CameraIF& camera( 
eCameraType, typename CameraIF::Tag = typename CameraIF::Tag() ) = 0;

对比:

virtual CameraControlIF_A& camera( 
eCameraType cameraID, CameraControlIF_A::Tag );

除了关于默认参数的问题,上面提到的防止歧义重载(在实现中)的技术是否常见?

最佳答案

当覆盖在基类中使用默认参数声明的 virtual 函数时,您可以添加另一个默认参数,它可以甚至不同的值(value)!但是,在覆盖函数中指定默认参数是一个非常糟糕的主意,使用不同的值会加倍如此。在任何情况下,您都不需要指定默认值,但您确实需要采用相应的参数,否则它不是覆盖函数:要覆盖的函数必须匹配基类声明完全相同(除了返回类型可以是协变的,如果它是指针或引用)。在 C++ 中(自 2011 年修订版起),您还可以在覆盖声明之后使用 override [上下文] 关键字让编译器验证该声明确实是一个覆盖。

关于c++ - 未命名的默认参数以防止歧义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20023794/

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