# Detecting field names with C++ metaprogramming

DevFeed: [Detecting field names with C++ metaprogramming](<https://devfeed.tech/articles/detecting-field-names-with-c-metaprogramming-40505.md>)

Original publisher: [Read original article](<https://www.jeremykun.com/shortform/2024-06-25-1534/>)

Published: 2024-06-25T22:34:59Z

Content type: tutorial

Language: en

Sources: [Jeremy Kun](<https://devfeed.tech/sources/jeremy-kun.md>)

Topics: [C++](<https://devfeed.tech/topics/c-plus-plus.md>), [Code](<https://devfeed.tech/topics/code.md>), [Template](<https://devfeed.tech/topics/template.md>)

Tags: [c-plus-plus](<https://devfeed.tech/tags/c-plus-plus.md>), [code](<https://devfeed.tech/tags/code.md>), [metaprogramming](<https://devfeed.tech/tags/metaprogramming.md>), [shortform](<https://devfeed.tech/tags/shortform.md>), [template](<https://devfeed.tech/tags/template.md>), [templates](<https://devfeed.tech/tags/templates.md>)

## AI overview

This short note explains how C++11 templates can detect whether a struct has a field with a specific name and type, then use the result for compile-time branching. It presents a SFINAE-based implementation using HasStaticSize and type traits.

## Source excerpt

A quick note: you can use C++11 templates to detect struct fields by name and type, and statically branch on them. I first heard of this solution from breeze1990. Say I want to detect if a struct has a field size of type int. Create two template instantiations of the same name, here HasStaticSize that defaults to false. #include <type_traits> template <typename T, typename = void> struct HasStaticSize : std::false_type {}; template <typename T> struct HasStaticSize< T, typename std::enable_if< std::is_same<int, std::decay_t<decltype(T::size)>>::value, void>::type> : std::true_type {}; The latter is only resolved if T::size is declared as int, or more specifically, something that "decays" to int.