使用共享指针功能重载

时间:2018-01-26 09:17:01

标签: c++ overloading shared-ptr

我曾预料到这会起作用,但在编译期间我会收到错误,如果有人能指出我的错误或我应该如何解决它将非常感激。最好不要求助于演员表。有这样的标准设计模式吗?

我做了一个简单的代码示例,显示了问题和我的意图。我有一个(通常是抽象的)基类(形状)与派生类(Square,Circle)。我有对对象的shared_ptr引用,并希望在基于shared_ptr类型的不同调用中执行相应的函数。

下面是代码不能正常工作,缺乏动态类型转换和丑陋的if语句,我不知道如何纠正它。

//Standard includes
#include "memory"
#include <typeinfo>

class Shape
{
public:
    virtual ~Shape() = default;
};
class Circle : public Shape { };
class Square : public Shape { };

class Logging
{
    static void print(std::shared_ptr<Circle> shape)
    {
        std::cout << "This object is a " << typeid(*shape).name() << std::endl;
    }

    static void print(std::shared_ptr<Square> shape)
    {
        std::cout << "This object is a " << typeid(*shape).name() << std::endl;
    }
};

int main() {
    //Shared Pointer Shape Declaration
    std::shared_ptr<Shape> circle = std::make_shared<Circle>();
    std::shared_ptr<Shape> square = std::make_shared<Square>();

    //Printing Shapes
    Logging::print(circle);     //Compiler ERROR: none of the 2 overloads could convert all the argument types
    Logging::print(square);     //Compiler ERROR: none of the 2 overloads could convert all the argument types

return 0;
}

提前感谢任何有用的答案。

2 个答案:

答案 0 :(得分:2)

您的问题在于从std::shared_ptr<Shape>std::shared_ptr<Circle>的向下转发。传递给函数时的上传,即使使用智能指针,也是自动的,但不是向下转换。因此,您的编译器找不到具有此签名的打印函数:

static void Logging::print(std::shared_ptr<Shape> shape);

你有一个过载错误。

但是,由于您在函数内部使用了解除引用运算符(*),并且由于std::shared_ptr重载了此运算符,因此可以使用template成员函数绕过此签名错误:

Logging print()函数的变体:

class Logging
{
    public:
    template <class T>
    static void print(std::shared_ptr<T> shape)
    {
        std::cout << "This object is a " << typeid(*shape).name() << std::endl;     
    }
};

How do add-in commands appear?。请记住,在使用模板时,如果您使用的是智能指针,请使用签名std::shared_ptr<T>

这样,您可以避免使用静态和动态转换。

答案 1 :(得分:1)

虽然allprojects { repositories { jcenter() google() maven { url "https://jitpack.io" } // that's the one missing. } } Shape是相关类型,但Squarestd::shared_ptr<Shape> 不是。这就是为什么它们之间没有任何隐式转换,所以你得到一个编译器错误。

一个非常经典的解决方案是将打印逻辑委托给从Shape派生的每个类:

std::shared_ptr<Square>

Working example

请注意,这只是一个示例,根据您的实际问题,此实现可能不实用/最佳。

相关问题