Qt Objects

The QObject class is the base class of all Qt objects

Q_OBJECT Macro

The Q_OBJECT Macro is probably one of the weirdest things to whoever beginning to use Qt.

Qt QObject Class says:

The Q_OBJECT macro must appear in the private section of a class definition that declares its own signals and slots or that uses other services provided by Qt’s meta-object system.

class MyClass : public QObject
{
    Q_OBJECT

public:
    MyClass(QObject *parent = 0);
    ~MyClass();

signals:
    void mySignal();

public slots:
    void mySlot();
};
class MyClass : public QObject
{
    Q_OBJECT
    Q_PROPERTY(Priority priority READ priority WRITE setPriority)
    Q_ENUMS(Priority)

public:
    enum Priority { High, Low, VeryHigh, VeryLow };

    MyClass(QObject *parent = 0);
    ~MyClass();

    void setPriority(Priority priority) { m_priority = priority; }
    Priority priority() const { return m_priority; }

private:
    Priority m_priority;

So, it sounds like we need it to use signal and slot, and probably for other purposes (meta-object related) as well.

Another doc related to moc explains:

The Meta-Object Compiler, moc, is the program that handles Qt’s C++ extensions.

The moc tool reads a C++ header file. If it finds one or more class declarations that contain the Q_OBJECT macro, it produces a C++ source file containing the meta-object code for those classes. Among other things, meta-object code is required for the signals and slots mechanism, the run-time type information, and the dynamic property system.

moc limitations

Multiple Inheritance Requires QObject to Be First

// correct
class SomeClass : public QObject, public OtherClass
{
    ...
};

Function Pointers Cannot Be Signal or Slot Parameters

class SomeClass : public QObject
{
    Q_OBJECT

public slots:
    void apply(void (*apply)(List *, void *), char *); // WRONG
};

// instead you can do next
typedef void (*ApplyFunction)(List *, void *);

class SomeClass : public QObject
{
    Q_OBJECT

public slots:
    void apply(ApplyFunction, char *);
};

Nested Classes Cannot Have Signals or Slots

class A
{
public:
    class B
    {
        Q_OBJECT

    public slots:   // WRONG
        void b();
    };
};

Signal/Slot return types cannot be references

Only Signals and Slots May Appear in the signals and slots Sections of a Class

QMetaObject

The QMetaObject class contains meta-information about Qt objects

The Qt Meta-Object System in Qt is responsible for the signals and slots inter-object communication mechanism, runtime type information, and the Qt property system. A single QMetaObject instance is created for each QObject subclass that is used in an application, and this instance stores all the meta-information for the QObject subclass. This object is available as QObject::metaObject().

This class is not normally required for application programming, but it is useful if you write meta-applications, such as scripting engines or GUI builders.

The functions you are most likely to find useful are these:

The index functions indexOfConstructor(), indexOfMethod(), indexOfEnumerator(), and indexOfProperty() map names of constructors, member functions, enumerators, or properties to indexes in the meta-object. For example, Qt uses indexOfMethod() internally when you connect a signal to a slot.

Classes can also have a list of namevalue pairs of additional class information, stored in QMetaClassInfo objects. The number of pairs is returned by classInfoCount(), single pairs are returned by classInfo(), and you can search for pairs with indexOfClassInfo().

Q_INVOKABLE void fun();
emmiter->metaObject()->method(emmiter->metaObject()->indexOfMethod("fun()")).invoke(emmiter,Qt::ConnectionType::DirectConnection,Q_ARG(QObject*, emmiter));

private slots:
    void MySlot(QObject* obj);

QMetaObject::invokeMethod(emmiter,"MySlot",Qt::ConnectionType::DirectConnection,Q_ARG(QObject*, emmiter));
//invoke methods defined with public slots or private slots or Q_INVOKABLE 

class Test:QObject
{
    Q_OBJECT
public:
    enum Myen{A,B,C};
    Q_ENUM(Myen);

    Test();
    Q_INVOKABLE void fun(Test::Myen en);
};
Q_DECLARE_METATYPE(Test::Myen);


bool b=QMetaObject::invokeMethod(this,"fun",Qt::ConnectionType::QueuedConnection,Q_ARG(Test::Myen,A));

//call fun function Test::A

QObject  Structure

QObjects organize themselves in object trees. When you create a QObject with another object as parent, the object will automatically add itself to the parent’s children() list. The parent takes ownership of the object; i.e., it will automatically delete its children in its destructor. You can look for an object by name and optionally type using findChild() or findChildren().

QObject(QObject *parent = nullptr)
parent() const
setParent(QObject *parent)
objectName() const
setObjectName(const QString &name)
findChild(const QString &name = QString(), Qt::FindChildOptions options = Qt::FindChildrenRecursively) 
findChildren(const QString &name = QString(), Qt::FindChildOptions options = Qt::FindChildrenRecursively)
children() const

inherits check

QTimer *timer = new QTimer;         // QTimer inherits QObject
timer->inherits("QTimer");          // returns true
timer->inherits("QObject");         // returns true
timer->inherits("QAbstractButton"); // returns false

// QVBoxLayout inherits QObject and QLayoutItem
QVBoxLayout *layout = new QVBoxLayout;
layout->inherits("QObject");        // returns true
layout->inherits("QLayoutItem");    // returns true (even though QLayoutItem is not a QObject)

QObject *obj = new QTimer;          // QTimer inherits QObject

QTimer *timer = qobject_cast<QTimer *>(obj);
// timer == (QObject *)obj

QAbstractButton *button = qobject_cast<QAbstractButton *>(obj);
// button == nullptr

Dynamic Properties (QMetaProperty)

class MyClass: public QObject
{
    Q_OBJECT
    Q_PROPERTY(Priority priority READ priority WRITE setPriority NOTIFY priorityChanged)

public:
    MyClass(QObject *parent = 0);
    ~MyClass();

    enum Priority { High, Low, VeryHigh, VeryLow };
    Q_ENUM(Priority)//registered as QMetaEnum

    void setPriority(Priority priority)// is not diffrent if private or public
    {
        m_priority = priority;
        emit priorityChanged(priority);
    }
    Priority priority() const
    { return m_priority; }

signals:
    void priorityChanged(Priority);

private:
    Priority m_priority;
};

MyClass *myinstance = new MyClass;
QObject *object = myinstance;

myinstance->setPriority(MyClass::VeryHigh);
object->setProperty("priority", "VeryHigh");
property(const char *name) const//call read function or get value of member
bool QObject::setProperty(const char *name, const QVariant &value)//call write function or set value to member
class Test:QObject
{
    Q_OBJECT
public:
    enum Myen{A,B,C};
    Q_ENUM(Myen);

    Test();
    Q_INVOKABLE void fun(Test::Myen en);// once you declare metataype as Test::Myen the argument should to be Test::Myen
};
Q_DECLARE_METATYPE(Test::Myen);

class A{
public:
    operator QString(){
        return QStringLiteral("A");
    }
};
Q_DECLARE_METATYPE(A);
Test::Test()
{
    QString retval;
    bool b=QMetaObject::invokeMethod(this,"fun",Qt::ConnectionType::QueuedConnection,Q_ARG(Test::Myen,A));
    qDebug()<<"end constructor";
}

void Test::fun(Test::Myen en)
{
    qDebug()<<"call fun function"<<en;
}

Signals and Slots

observer design pattern
#include <QApplication>
#include <QPushButton>
int main(int argc, char *argv[])
{
   QApplication app(argc, argv);
   QPushButton *quitButton = new QPushButton("Quit");
   QObject::connect(quitButton, SIGNAL(clicked()),
           &app, SLOT(quit()));
   quitButton->show();
return app.exec();
}

A signal can also be connected to another signal:

class MyWidget::public QWidget
{
    Q_OBJECT

public:
    MyWidget();

signals:
    void buttonClicked();

private:
    QPushButton *myButton;
};

MyWidget::MyWidget()
{
    myButton = new QPushButton(this);
    connect(myButton, SIGNAL(clicked()),
            this, SIGNAL(buttonClicked()));
}

The signal must be a function declared as a signal in the header. The slot function can be any member function that can be connected to the signal. A slot can be connected to a given signal if the signal has at least as many arguments as the slot, and there is an implicit conversion between the types of the corresponding arguments in the signal and the slot.

QLabel *label = new QLabel;
QLineEdit *lineEdit = new QLineEdit;
QObject::connect(lineEdit, &QLineEdit::textChanged,
                 label,  &QLabel::setText);
connect(const QObject *sender, const char *signal, const QObject *receiver, const char *method, Qt::ConnectionType type = Qt::AutoConnection)
connect(const QObject *sender, const QMetaMethod &signal, const QObject *receiver, const QMetaMethod &method, Qt::ConnectionType type = Qt::AutoConnection)
connect(const QObject *sender, PointerToMemberFunction signal, const QObject *receiver, PointerToMemberFunction method, Qt::ConnectionType type = Qt::AutoConnection)
connect(const QObject *sender, PointerToMemberFunction signal, Functor functor)
connect(const QObject *sender, PointerToMemberFunction signal, const QObject *context, Functor functor, Qt::ConnectionType type = Qt::AutoConnection)
all connect functions return QMetaObject::Connection we can use it for disconnect later

enum Qt::ConnectionType

This enum describes the types of connection that can be used between signals and slots. In particular, it determines whether a particular signal is delivered to a slot immediately or queued for delivery at a later time.

Constant
Qt::AutoConnection
(Default) If the receiver lives in the thread that emits the signal, Qt::DirectConnection is used. Otherwise, Qt::QueuedConnection is used. The connection type is determined when the signal is emitted.
Qt::DirectConnection
The slot is invoked immediately when the signal is emitted. The slot is executed in the signalling thread.
Qt::QueuedConnection
The slot is invoked when control returns to the event loop of the receiver’s thread. The slot is executed in the receiver’s thread.
Qt::BlockingQueuedConnection
Same as Qt::QueuedConnection, except that the signalling thread blocks until the slot returns. This connection must not be used if the receiver lives in the signalling thread, or else the application will deadlock.
Qt::UniqueConnection
This is a flag that can be combined with any one of the above connection types, using a bitwise OR. When Qt::UniqueConnection is set, QObject::connect() will fail if the connection already exists (i.e. if the same signal is already connected to the same slot for the same pair of objects). This flag was introduced in Qt 4.6.
#include <QtCore>

class Test : public QObject
{
    Q_OBJECT
public:
    explicit Test(QObject *parent = nullptr);

signals:
    void MySignal();
public:
    void EmitSignal();
public slots://not necesorry only if you wnat to use it as SLOT(MySlot())
    void MySlot();

};
#include "test.h"

Test::Test(QObject *parent) : QObject(parent)
{

}

void Test::EmitSignal(){
    emit this->MySignal();
    qDebug()<<"signal is emmited";
}

void Test::MySlot(){
    qDebug()<<"slot is called"<<sender();
}

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);
    Test emmiter,reciver;

    QObject::connect(&emmiter,&Test::MySignal,&reciver,&Test::MySlot,Qt::ConnectionType::QueuedConnection);
    //print signal is emmited then slot is called
    
    QObject::connect(&emmiter,&Test::MySignal,&reciver,&Test::MySlot,Qt::ConnectionType::DirectConnection);
    //print slot is called then signal is emmited

    emmiter.EmitSignal();
    return a.exec();
}

there are many ways to add signal and slot to connect

QObject::connect(&emmiter,SIGNAL(MySignal()),&reciver,SLOT(MySlot()));//slot here should to be Q_INVOKABLE or public private slots:
QObject::connect(&emmiter,&Test::MySignal,&reciver,&Test::MySlot)// slot here can be any function member of object

disconnect

disconnect(const QObject *sender, const char *signal, const QObject *receiver, const char *method)
disconnect(const QObject *sender, const QMetaMethod &signal, const QObject *receiver, const QMetaMethod &method)
disconnect(const QMetaObject::Connection &connection)
disconnect(const QObject *sender, PointerToMemberFunction signal, const QObject *receiver, PointerToMemberFunction method)
all of them return bool value

before we were use public static method to connect and disconnect but actually you can use public non-static members

disconnect(const char *signal = nullptr, const QObject *receiver = nullptr, const char *method = nullptr)
connect(const QObject *sender, const char *signal, const char *method, Qt::ConnectionType type = Qt::AutoConnection)
disconnect(const QObject *receiver, const char *method = nullptr) const
void blockSignals(bool block) // non-static member to block any signal come from this object
bool signalsBlocked() const// to check if signals comming from this object is blocked or not
int	receivers(const char *signal) const //protected method number of recivers
QObject *	sender() const // protected method can use it inside any slot to get the sender object
int	senderSignalIndex() const //meta-method index of the signal that called the currently executing slot
QCoreApplication a(argc, argv);
Test *emmiter=new Test{} ,*reciver=new Test{};
QObject::connect(emmiter,&Test::destroyed,reciver,&Test::MySlot);
qDebug()<<emmiter;
delete emmiter;
return a.exec();
//===============================
void Test::MySlot(QObject* obj){
    qDebug()<<"slot is called \n"<<obj;
}

QSignalMapper

QGridLayout *gridLayout = new QGridLayout(this);
QSignalMapper *mapper = new QSignalMapper(this);
for(int row = 0; row < 3; ++row) {
    for(int column = 0; column < 3; ++column) {
        QPushButton *button = new QPushButton(" ");
        gridLayout->addWidget(button, row, column);
        m_board.append(button);
        mapper->setMapping(button, m_board.count() - 1);
        connect(button, SIGNAL(clicked()), mapper, SLOT(map()));
    }
}
connect(mapper, SIGNAL(mapped(int)),
        this,   SLOT(handleButtonClick(int)));

QObject predefined signals and slots

deleteLater()
destroyed(QObject *obj = nullptr)
objectNameChanged(const QString &objectName)

Events System

Qt creates an event object to represent it by constructing an instance of the appropriate QEvent subclass, and delivers it to a particular instance of QObject (or one of its subclasses) by calling its event() function.
This function does not handle the event itself; based on the type of event delivered, it calls an event handler for that specific type of event, and sends a response based on whether the event was accepted or ignored.

bool MyWidget::event(QEvent *event)
{
    if (event->type() == QEvent::KeyPress) {
        QKeyEvent *ke = static_cast<QKeyEvent *>(event);
        if (ke->key() == Qt::Key_Tab) {
            // special tab handling here
            return true;
        }
    } else if (event->type() == MyCustomEventType) {
        MyCustomEvent *myEvent = static_cast<MyCustomEvent *>(event);
        // custom event handling here
        return true;
    }

    return QWidget::event(event);
}

Note that event() is still called for all of the cases not handled, and that the return value indicates whether an event was dealt with; a true value prevents the event from being sent on to other objects.

protected:
    bool event(QEvent *event) override{
        qDebug()<<"call event \n";
        QObject::event(event);//call timerEvent
        return false;
    }

    void timerEvent(QTimerEvent *event) override{
        qDebug()<<"call timer event \n";
    }

    bool eventFilter(QObject *watched, QEvent *event) override{
        //watched = pointer to object carch event
        qDebug()<<"call event filter \n";
        return false; // false meen can call event function
    }


    Test t;
    t.startTimer(1000);
    t.installEventFilter(&t);
call event filter
call event
call timer event

When the filter object’s eventFilter() implementation is called, it can accept or reject the event, and allow or deny further processing of the event. If all the event filters allow further processing of an event (by each returning false), the event is sent to the target object itself. If one of them stops processing (by returning true), the target and any later event filters do not get to see the event at all.

Sending Events

Many applications want to create and send their own events. You can send events in exactly the same ways as Qt’s own event loop by constructing suitable event objects and sending them with QCoreApplication::sendEvent() and QCoreApplication::postEvent().

sendEvent() processes the event immediately. When it returns, the event filters and/or the object itself have already processed the event. For many event classes there is a function called isAccepted() that tells you whether the event was accepted or rejected by the last handler that was called.

postEvent() posts the event on a queue for later dispatch. The next time Qt’s main event loop runs, it dispatches all posted events, with some optimization. For example, if there are several resize events, they are compressed into one. The same applies to paint events: QWidget::update() calls postEvent(), which eliminates flickering and increases speed by avoiding multiple repaints.

postEvent() is also used during object initialization, since the posted event will typically be dispatched very soon after the initialization of the object is complete. When implementing a widget, it is important to realize that events can be delivered very early in its lifetime so, in its constructor, be sure to initialize member variables early on, before there’s any chance that it might receive an event.

To create events of a custom type, you need to define an event number, which must be greater than QEvent::User, and you may need to subclass QEvent in order to pass specific information about your custom event. See the QEvent documentation for further details.

Q_GADGET

The Q_GADGET macro is a lighter version of the Q_OBJECT macro for classes that do not inherit from QObject but still want to use some of the reflection capabilities offered by QMetaObject. Just like the Q_OBJECT macro, it must appear in the private section of a class definition.

Q_GADGETs can have Q_ENUMQ_PROPERTY and Q_INVOKABLE, but they cannot have signals or slots.

Q_GADGET makes a class member, staticMetaObject, available. staticMetaObject is of type QMetaObject and provides access to the enums declared with Q_ENUMS.

links
https://doc.qt.io/qt-5/qobject.html
https://doc.qt.io/qt-5/qmetaobject.html

Resonance Circuits

Resonance in AC circuits implies a special frequency determined by the values of the resistance , capacitance , and inductance . For series resonance the condition of resonance is straightforward and it is characterized by minimum impedance and zero phase. Parallel resonance , which is more common in electronic practice, requires a more careful definition.This is an active graphic. Click on either for more detail.

Series Resonance

The resonance of a series RLC circuit occurs when the inductive and capacitive reactances are equal in magnitude but cancel each other because they are 180 degrees apart in phase. The sharp

inductive reactance against frequencycapacitive reactance against frequencyseries resonance frequency

minimum in impedance which occurs is useful in tuning applications. The sharpness of the minimum depends on the value of R and is characterized by the “Q” of the circuit.

series RLC circuit at resonance

Since the current flowing through a series resonance circuit is the product of voltage divided by impedance, at resonance the impedance, Z is at its minimum value, ( =R ). Therefore, the circuit current at this frequency will be at its maximum value of V/R as shown below.

series RLC circuit current at resonance

As a series resonance circuit only functions on resonant frequency, this type of circuit is also known as an Acceptor Circuit because at resonance, the impedance of the circuit is at its minimum so easily accepts the current whose frequency is equal to its resonant frequency.
Phase Angle of a Series Resonance Circuit

Phase angle at resonance

Parallel Resonance

parallel resonance circuit

Let us define what we already know about parallel RLC circuits.

parallel rlc circuit

The resonance of a parallel RLC circuit is a bit more involved than the series resonance. The resonant frequency can be defined in three different ways, which converge on the same expression as the series resonant frequency if the resistance of the circuit is small.

parallel resonant circuit stores the circuit energy in the magnetic field of the inductor and the electric field of the capacitor. This energy is constantly being transferred back and forth between the inductor and the capacitor which results in zero current and energy being drawn from the supply.

This is because the corresponding instantaneous values of IL and IC will always be equal and opposite and therefore the current drawn from the supply is the vector addition of these two currents and the current flowing in IR.

parallel circuit admittanceparallel resonance equation

Also at resonance the parallel LC tank circuit acts like an open circuit with the circuit current being determined by the resistor, R only. So the total impedance of a parallel resonance circuit at resonance becomes just the value of the resistance in the circuit and  Z = R as shown.

parallel resonance

Z=(Xc*Xl)/(Xl-Xc) = infinity when Xl=Xc so it is kind of open

parallel rlc currents at resonanceparallel resonance circuit impedance

resonances circuits

the wave is appear once switch is open
close switch at the point to feed LC tank
Armstrong resonant circuit
colpitts resonant circuit
hartley resonant circuit
crystal
colpetts with crystal
hartley with crystal
pierce crystal resonant circuit
example

Inductive Proximity Sensor

inductive proximity sensor can detect metal targets approaching the sensor, without physical contact with the target. Inductive Proximity Sensors are roughly classified into the following three types according to the operating principle: the high-frequency oscillation type using electromagnetic induction, the magnetic type using a magnet, and the capacitance type using the change in capacitance.

General sensor

General sensor

A high-frequency magnetic field is generated by coil L in the oscillation circuit. When a target approaches the magnetic field, an induction current (eddy current) flows in the target due to electromagnetic induction. As the target approaches the sensor, the induction current flow increases, which causes the load on the oscillation circuit to increase. Then, oscillation attenuates or stops. The sensor detects this change in the oscillation status with the amplitude detecting circuit, and outputs a detection signal.

General sensor

Nonferrousmetal type

The nonferrous-metal type is included in the high-frequency oscillation type. The nonferrous-metal type incorporates an oscillation circuit in which energy loss caused by the induction current flowing in the target affects the change of the oscillation frequency. When a nonferrous-metal target such as aluminum or copper approaches the sensor, the oscillation frequency increases. On the other hand, when a ferrous-metal target such as iron approaches the sensor, the oscillation frequency decreases. When the oscillation frequency becomes higher than the reference frequency, the sensor outputs a detection signal.

Nonferrousmetal type

Magnetic objects and non-magnetic objects Remember that magnetic objects are easily attracted by a magnet, whereas non-magnetic objects are not.

MagnetismMagnetism
Detecting distance of general-purpose modelDetecting distance of
general-purpose model
Detecting distance of aluminum detection modelDetecting distance of
aluminum detection model
Typical metalIron – SUS304* – Aluminum/copper

Rvalue References

Understand std::move

Because std::move does nothing but cast its argument to an rvalue, there have been
suggestions that a better name for it might have been something like rvalue_cast.

//c++11
template<typename T> // in namespace std
typename remove_reference<T>::type&&
move(T&& param)
{
 using ReturnType = // alias declaration;
 typename remove_reference<T>::type&&;
 return static_cast<ReturnType>(param);
}

// C++14; still in
template<typename T>
decltype(auto) move(T&& param) // namespace std
{
 using ReturnType = remove_reference_t<T>&&;
 return static_cast<ReturnType>(param);
}

Distinguish universal references from rvalue
references.

• If a function template parameter has type T&& for a deduced type T, or if an object is declared using auto&&, the parameter or object is a universal reference.
• If the form of the type declaration isn’t precisely type&&, or if type deduction does not occur, type&& denotes an rvalue reference.
• Universal references correspond to rvalue references if they’re initialized with rvalues. They correspond to lvalue references if they’re initialized with lvalues.

void f(Widget&& param); // rvalue reference
Widget&& var1 = Widget(); // rvalue reference
auto&& var2 = var1; // is a universal reference
template<typename T>
void f(std::vector<T>&& param); // rvalue reference
template<typename T>
void f(T&& param); // is a universal reference
template<typename T>
void f(std::vector<T>&& param); // param is an rvalue reference
std::vector<int> v;
f(v); // error! can't bind lvalue to
 // rvalue reference
auto timeFuncInvocation =
 [](auto&& func, auto&&... params) // C++14
 {
 start timer;
 std::forward<decltype(func)>(func)( // invoke func
 std::forward<decltype(params)>(params)... // on params
 );
 stop timer and record elapsed time;
 };

Use std::move on rvalue references,
std::forward on universal references.

• Apply std::move to rvalue references and std::forward to universal refer‐
ences the last time each is used.
• Do the same thing for rvalue references and universal references being
returned from functions that return by value.
• Never apply std::move or std::forward to local objects if they would other‐
wise be eligible for the return value optimization.

class Widget {
public:
 Widget(Widget&& rhs) // rhs is rvalue reference
 : name(std::move(rhs.name)),
 p(std::move(rhs.p))
 { … }
 …
private:
 std::string name;
 std::shared_ptr<SomeDataStructure> p;
};
class Widget {
public:
 template<typename T>
 void setName(T&& newName) // newName is
 { name = std::forward<T>(newName); } // universal reference
 …
};

using std::move with universal references,that can have the
effect of unexpectedly modifying lvalues

Matrix // by-value return
operator+(Matrix&& lhs, const Matrix& rhs)
{
 lhs += rhs;
 return std::move(lhs); // move lhs into
} 

Matrix // as above
operator+(Matrix&& lhs, const Matrix& rhs)
{
 lhs += rhs;
 return lhs; // copy lhs into
} 

template<typename T>
Fraction // by-value return
reduceAndCopy(T&& frac) // universal reference param
{
 frac.reduce();
 return std::forward<T>(frac); // move rvalue into return
} 

don’t move local variable into return value

Widget makeWidget() // Moving version of makeWidget
{
 Widget w;
 …
 return std::move(w); // move w into return value
} 

Avoid overloading on universal references

std::multiset<std::string> names; // global data structure
void logAndAdd(const std::string& name)
{
 auto now = // get current time
 std::chrono::system_clock::now();
 log(now, "logAndAdd"); // make log entry
 names.emplace(name); // add name to global data
} 
std::string petName("Darla");
logAndAdd(petName); // pass lvalue std::string
logAndAdd(std::string("Persephone")); // pass rvalue std::string
logAndAdd("Patty Dog"); // pass string literal

in the previous example in second and third call name itself is an lvalue, so it’s copied into names.

template<typename T>
void logAndAdd(T&& name)
{
 auto now = std::chrono::system_clock::now();
 log(now, "logAndAdd");
 names.emplace(std::forward<T>(name));
}
std::string petName("Darla"); // as before
logAndAdd(petName); // as before, copy lvalue into multiset
logAndAdd(std::string("Persephone")); // move rvalue instead of copying it
logAndAdd("Patty Dog"); // create std::string in multiset instead of copying a temporary std::string

Constraining templates that take universal references

Alternatives to the combination of universal references and overloading
include the use of distinct function names, passing parameters by lvaluereference-to-const, passing parameters by value, and using tag dispatch.
• Constraining templates via std::enable_if permits the use of universal references and overloading together, but it controls the conditions under which compilers may use the universal reference overloads.
• Universal reference parameters often have efficiency advantages, but they typically have usability disadvantages.

class Person {
public:
 template<
 typename T,
 typename = typename std::enable_if<!std::is_base_of<Person,typename std::decay<T>::type>::value>::type>
 explicit Person(T&& n);
 …
};

//c++14
class Person {
public:
 template<
 typename T,
 typename = std::enable_if_t<!std::is_base_of<Person,std::decay_t<T>>::value>>
 explicit Person(T&& n);
 …
};

#include <type_traits>

template<typename T>
class YourClass {

    YourClass() {
        // Compile-time check
        static_assert(std::is_base_of<BaseClass, T>::value, "type parameter of this class must derive from BaseClass");

        // ...
    }
}
class Person {
public:
    template<typename T,typename = std::enable_if_t<std::is_base_of_v<Person,std::decay_t<T>>>>
    explicit Person(T&& n){
    }
    Person()= default;
};
int main(int argc,char* argv[]){
    Person pp;
    Person p(pp);
    return 0;
}