Why is TSharedFromThis used in ShooterGame for inheritance?

I stumbled across this while studying the ShooterGame example and the Slate menu implementation:

class FShooterMainMenu : public TSharedFromThis<FShooterMainMenu>

This feels like it shouldn’t work as you are inheriting yourself, but how is this working and what is the usages of TSharedFrommThis?

1 Like

It’s a C++ templating trick, you use your own class as the template argument, so that when the templating occurs in the compiler it generates code using your class in all the locations the template argument was used. You’re not actually inheriting from yourself, you’re inheriting from a template that is parameterized with your class :slight_smile:

TSharedFromThis is so that we can more easily get the TSharedPtr that has already been allocated somewhere that’s holding onto an instance of this class. Slate uses this a lot so that widgets can pass themselves around as a shared reference by inherting from this class and using SharedThis(this).

Cheers,
Nick

3 Likes

The concept is known as the Curiously Recurring Template Pattern (or CRTP for short), if you want to read up on it a bit more:

Steve

2 Likes

Hello,

Apologies for reviving this thread but I was wondering how we could inherit from the TSharedFromThis template.

I was not able to find this via the “Add new C++ class” option in the editor.

Thanks in advance.

Apologies for reviving this thread but I was wondering how we could inherit from the TSharedFromThis template.

I was not able to find this via the “Add new C++ class” option in the editor.

I do not believe this is possible through the editor / BPs (though I might be wrong as I spend 95% of the time in C++).

When creating a new class FYourClass, you need to make it a child of TSharedFromThis, so TSharedFromThis<FYourClass>.

Here is a minimal version of the ISceneOutlinerTreeItem.h header, which (roughly speaking) is used for connecting the rows in the Scene Outliner with their underlying data.

// Copyright Epic Games, Inc. All Rights Reserved.

#pragma once

#include "CoreMinimal.h"

/** Base tree item interface  */
struct SCENEOUTLINER_API ISceneOutlinerTreeItem : TSharedFromThis<ISceneOutlinerTreeItem>
{
...
};

As you can see, the struct ISceneOutlinerTreeItem is passed to the TSharedFromThis template, resulting in template instantiation. You can find TSharedFromThis inside the SharedPointer.h header. Classes can also be used, as exemplified by the class ISceneOutlinerColumn (ISceneOutlinerColumn.h).

Hello,

I vaguely remember trying something like this if not exactly this and getting a compiler error.

I’ve moved on from the problem but I’ll go back and check on this when I can.

Thanks for the info.