0

I am using template to write a class, which can dirivate from every class.

I have two versions, one called God and the other called Helper. The code is similar.

The code shows that :

#include <memory>
#include <iostream>
class ClassArgsZero
{
public:
    ClassArgsZero()
    {
        std::cout << "ClassArgsZero construct" << std::endl;
    }

private:
};

class ClassArgsTwo
{
public:
    ClassArgsTwo(int x_, std::string y_)
        : x(x_), y(y_)
    {
        std::cout << "ClassArgsTwo construct" << std::endl;
    }

private:
    int x;
    std::string y;
};

template <typename Object, typename... Args>
void function(Args &&... args)
{
    class Helper : public Object
    {
    public:
        Helper(Args &&... args)
            : Object{std::forward<Args>(args)...}
        {
            std::cout << "Helper construct" << std::endl;
        }
    };
    Helper help(std::forward<Args>(args)...);
}

template <typename Object, typename... Args>
class God : public Object
{
public:
    God(Args &&... args)
        : Object{std::forward<Args>(args)...}
    {
        std::cout << "God construct" << std::endl;
    }

private:
};

int main()
{
    God<ClassArgsTwo, int, std::string> god_1(2, "string");
    God<ClassArgsZero> god_2(); // why not construct?

    function<ClassArgsTwo, int, std::string>(2, "string");
    function<ClassArgsZero>(); // why construct here?

    return 0;
}

One can use the following command to compile it and run it:

$ g++ main.cpp
$ ./a.out

The output shows that:

ClassArgsTwo construct
God construct
ClassArgsTwo construct
Helper construct
ClassArgsZero construct
Helper construct

The result shows that the object god_2 is not built, since I am God is not printed in the terminal.

I do not totally uderstand why the object God has not been built with the base class ClassArgsZero.

I am also confused that the object Helper can be built with the base class ClassArgsZero. Why is that?

Thanks in advance for the help.

Xu Hui
  • 1,213
  • 1
  • 11
  • 24

0 Answers0