Does Boost additionally recognize inheritance?

class Base {};
class Derived : public Base {};

void func(boost::optional<Base>&) {}

int main () {
  boost::optional<Derived> x;
  func(x);
}

will func accept both options: base and derivatives?

+4
source share
2 answers

No, that will not work. functakes the lvalue value for boost::optional<Base>. This means that it can take an lvalue of a type boost::optional<Base>, an lvalue of a type that is publicly and explicitly inferred from boost::optional<Base>or of another type c operator boost::optional<Base>&(). None of them apply to boost::optional<Derived>. Class templates are not coviarant in a system like C ++ - boost::optional<Derived>not inherited from boost::optional<Base>.


It would be different if I funcaccepted my argument by value. If it looked like this:

void func(boost::optional<Base> ) { }

func boost::optional<Derived>. explicit, :

func(boost::optional<Base>{x});

, - , () x.

+4

(, ), . Base .

, Base. Base , Derived ( ), Base.


EDIT:

, :

int main () {
  boost::optional x(Derived());
  func(x);
}

:

  • boost::optional
  • .

, - :

int main () {
  boost::optional<Base> x = Derived();
  func(x);
}

( , Visual Studio 2013 Boost 1.60) . :

#include <boost/optional.hpp>
#include <iostream>

class Base
{
public:
    virtual ~Base() { std::cout << "~Base" << std::endl; }
};

class Derived : public Base
{
public:
    virtual ~Derived() { std::cout << "~Derived" << std::endl; }
};

int main()
{
    boost::optional<Base> x = Derived();
}

~Derived
~Base
~Base

~Base , optional Base, Derived. (~Derived Derived(), ~Base.)

-1

All Articles