Tuesday Coding Tip 24 — Getting template type from an existing object

●4 ●15 ●74
calendar_today • schedule1 min read
— Originally published at medium.com

Tuesday coding tips are super short posts about various tidbits mainly from C++, but also from other programming languages I use. You can also follow the #TuesdayCodingTips hashtag on Mastodon and Linkedin.


Nice APIs expose their template types as member aliases so that anybody can get them easily. For other types, you might be able to deduce the type by calling decltype on a return value of some of their functions.

Sometimes, none of that is possible. But there is still a way to get to it. You need to write a template structure that only matches on the type you care about and alias the template parameters so you can access them later, a technique known as ‘type trait’.

#include <vector>

// Base template, only for the compiler
template<class T>
struct UnderlyingVectorType {};

// Overload for vector, note that templates don't have to match
template<class T, class A>
struct UnderlyingVectorType<std::vector<T, A>> {
    using StorageType = T;
    using AllocatorType = A;
};

// Nice types already expose their template types
template<class T>
class NiceType {
public:
    using StorageType = T;
};

int main() {
    int a;
    
    // error: no type named 'type' in 'UnderlyingVectorType<int>'
    // because it resolves to the base template
    // UnderlyingVectorType<decltype(a)>::storageType b;

    std::vector<float> vec;
    using VecStorageType = UnderlyingVectorType<decltype(vec)>::StorageType;
    VecStorageType vec2;
    static_assert(std::is_same_v<VecStorageType, float>);

    NiceType<double> nice;
    decltype(nice)::StorageType myDouble = 0.0;
    static_assert(std::is_same_v<decltype(nice)::StorageType, double>);
}
Part 24 of 25 in Tuesday Coding Tips

1 Comment

1 vote
🔥 Join developers growing publicly
Share your knowledge, build in public, and grow your developer presence with a global community.

More Posts

Tuesday Coding Tip 06 - Explicit template instantiation

Jakub Neruda - Apr 7

Tuesday Coding Tip 02 - Template with type-specific API

Jakub Neruda - Mar 10

Tuesday Coding Tip 05 - Object initialization in C++

Jakub Neruda - Mar 31

Tuesday Coding Tip 08 — Explicit template specialization

Jakub Neruda - Apr 21

Tuesday Coding Tip 17 — Wrapping C APIs

Jakub Neruda - Jun 30
chevron_left
1.7k Points • 93 Badges
Brno, Czech Republic • linkedin.com/in/jakub-neruda
34Posts
28Comments
18Connections
Experienced C++ developer, team lead and hobby gamedev. I enjoy writing stuff about C++, clean code, clean architecture, and game development.

Related Jobs

View all jobs →

Commenters (This Week)

3 comments
1 comment
1 comment

Contribute meaningful comments to climb the leaderboard and earn badges!