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

●5 ●29 ●93
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>);
}

Want more #cpp & #tuesday-coding-tips deep dives?

Join 6,001+ developers sharing real benchmarks, code breakdowns, and projects. Free forever.

Part 24 of 31 in Tuesday Coding Tips

1 Comment

1 vote

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 08 — Explicit template specialization

Jakub Neruda - Apr 21

Tuesday Coding Tip 05 - Object initialization in C++

Jakub Neruda - Mar 31

Tuesday Coding Tip 31 — Deducing this

Jakub Neruda - Nov 17
chevron_left
2.1k Points • 127 Badges
Brno, Czech Republic • linkedin.com/in/jakub-neruda
43Posts
37Comments
22Connections
Experienced C++ developer, team lead and hobby gamedev. I enjoy writing stuff about C++, clean code, clean architecture, and game development.

Related Jobs

Commenters (This Week)

1 comment
1 comment

Contribute meaningful comments to climb the leaderboard and earn badges!