How to avoid repetitive code for static mesh and skeletal mesh components

I have a c++ class that contains both static mesh and skeletal mesh, as components. And I have blueprint instances deriving from this class. These blueprint instances could be either static mesh or skeletal mesh
My question is I am updating the material by writing same code for both static mesh and skeletal mesh which i think duplication, an object could be either static mesh or skeletal mesh when its spawned
Is there a way we can better handle it by making use of coding templates or some other way to avoid writing the same code twice

for (UStaticMeshComponent* sm : StaticMeshComponents)
	{
		if (UMaterialInterface* DefaultMaterial = sm->GetMaterial(IndexOfMaterialToMakeDynamic))
		{
			DynamicMaterialInstance = UMaterialInstanceDynamic::Create(DefaultMaterial, this);
			sm->SetMaterial(IMaterialDynamic, DynamicMaterialInstance);
		}
	}

	for (USkeletalMeshComponent* sm : SkeletalMeshComponents)
	{
		if (UMaterialInterface* DefaultMaterial = sm->GetMaterial(IndexOfMaterialToMakeDynamic))
		{
			DynamicMaterialInstance = UMaterialInstanceDynamic::Create(DefaultMaterial, this);
			sm->SetMaterial(MaterialDynamic, DynamicMaterialInstance);
		}
	}

You could use UMeshComponent from which both UStaticMeshComponent and USkeletalMeshComponent derive.

TSet<UMeshComponent*> MeshComponents;

if (StaticMeshComponents.Num())
{
    for (UStaticMeshComponent* sm : StaticMeshComponents)
    {
        MeshComponents.Add(sm);
    }
}
else
{
    for (USkeletalMeshComponent* sm : SkeletalMeshComponents)
    {
        MeshComponents.Add(sm);
    }
}

for (UMeshComponent* mc : MeshComponents)
{
	if (UMaterialInterface* DefaultMaterial = mc->GetMaterial(IndexOfMaterialToMakeDynamic))
	{
		DynamicMaterialInstance = UMaterialInstanceDynamic::Create(DefaultMaterial, this);
		mc->SetMaterial(IMaterialDynamic, DynamicMaterialInstance);
	}
}

Runtime DataTable : Import and export game data to and from CSV or Google Sheets while your game is running!

GSheets Operator : Interface with Google Sheets, add new and delete old sheets, edit columns and rows, make in-game spreadsheets and more!

easyCSV : Read data from any CSV and put them in an easy-to-access string map!

iTween : Free, smooth, procedural object animation