C++ Metaprogramming: Understanding and Using std::common_reference

2025-09-13

std::common_reference is a type trait that, given two or more types, finds a single type to which all the original types can be converted. This is particularly important when dealing with templates and generic programming, where you don't know the exact types beforehand. It's often used to determine the return type of a function that operates on different kinds of references or values.

One of the most frequent issues with std::common_reference is when the compiler can't figure out a suitable common type. This usually happens in these scenarios

Incompatible Types
When the types are fundamentally different and no implicit conversion path exists. For example, trying to find a common reference between int& and std::string& will fail because they are unrelated.

Constness and Volatility
The const and volatile qualifiers can be tricky. While std::common_reference is designed to handle this, sometimes the combination of types and qualifiers can lead to unexpected results or compilation errors. The common reference must be able to hold all the qualifiers from the original types.

Reference Collapsing Rules
When using templates, the rules for reference collapsing (e.g., T& & becomes T&) can interact in complex ways with std::common_reference, leading to surprising outcomes.

When std::common_reference doesn't work out, or you need a more explicit way to handle types, here are some great alternatives.

Sometimes you might want to find a common type for values, not references. In this case, std::common_type_t is the perfect tool. You can combine it with std::decay_t to strip away references and const/volatile qualifiers, giving you the fundamental underlying type.

Example
Imagine you have a function that returns the larger of two numbers, which could be an int or a double. std::common_reference might be too strict here.

#include <iostream>
#include <type_traits>

template <typename T, typename U>
auto max_val(T&& a, U&& b) {
    // std::common_type_t finds the common type for values.
    // std::decay_t strips references and qualifiers.
    using CommonType = std::common_type_t<std::decay_t<T>, std::decay_t<U>>;
    return static_cast<CommonType>(a > b ? a : b);
}

int main() {
    int i = 5;
    double d = 10.5;

    // The return type is double, which is the common type.
    auto result = max_val(i, d);
    std::cout << "Result: " << result << std::endl; // Output: 10.5

    return 0;
}

For more control, especially when dealing with complex or custom types, you can use if constexpr to define the return type explicitly based on conditions. This gives you a lot of flexibility and is a great way to handle types that std::common_reference might not support out of the box.

Example
Let's say you have a custom Vector class and want to return a reference to one of the vectors.

#include <iostream>
#include <vector>

template <typename T, typename U>
auto get_common_vec(T& t, U& u) {
    // Check if both types are vectors of the same element type.
    if constexpr (std::is_same_v<T, U>) {
        // If types are the same, we can return a reference to either.
        return t;
    } else {
        // If types are different, we might need to return a common value type
        // or handle the error gracefully. For simplicity, let's return a copy.
        // This is where you could add more complex logic.
        using CommonType = std::common_type_t<T, U>;
        return CommonType(t);
    }
}

int main() {
    std::vector<int> v1{1, 2, 3};
    std::vector<int> v2{4, 5, 6};

    auto& result = get_common_vec(v1, v2); // Returns a reference to v1.
    result[0] = 99; // Modifies v1.

    std::cout << "v1[0]: " << v1[0] << std::endl; // Output: 99

    return 0;
}

This is a classic C++ metaprogramming technique. decltype allows you to deduce the type of an expression, and std::declval creates an "rvalue reference" to a type without constructing an object. You can combine these to simulate an operation and get its return type.

Example
Suppose you want to find the return type of an operator+ between two different types.

#include <iostream>
#include <type_traits>

// A type trait to get the return type of the addition operator.
template <typename T, typename U>
using add_result_t = decltype(std::declval<T>() + std::declval<U>());

int main() {
    using ResultType = add_result_t<int, double>;

    // ResultType will be double, which is the type of 5 + 10.5.
    static_assert(std::is_same_v<ResultType, double>);
    
    std::cout << "add_result_t<int, double> is a double!" << std::endl;

    return 0;
}

This approach is powerful because it lets you define the "common" type based on the actual operation you intend to perform, rather than a generic rule.


cpp



Beyond Blocking: Asynchronous Programming with C++ Futures

First off, let's quickly review what std::future::get() does. When you're working with asynchronous operations (like a task running on a separate thread), std::future is an object that holds the result of that operation


Mastering std::countr_one in C++20: Pitfalls and Pre-C++ Alternatives

In C++ (since C++20), the function std::countr_one(x) is a numerical operation that counts the number of consecutive 1 bits in the value of x, starting from the least significant bit (the "right" side)


The "Most Vexing Parse" in C++: A Guide to Direct and Brace Initialization

Direct initialization is one of the ways to initialize an object in C++. It uses parentheses () to construct an object directly from an initializer



C++ bitor: Understanding the Bitwise OR Keyword

The bitor keyword is an alternative representation for the bitwise OR operator (|). It's part of a set of alternative operator keywords that were introduced to make C++ code more accessible for developers whose keyboards or character sets didn't easily support special symbols like |, ^, or &. While it's still part of the C++ standard


Troubleshooting C++ std::source_location: Common Issues and Alternatives

While std::source_location is great, there are a few common pitfalls you might run intoThis is the most frequent issue. std::source_location is a C++20 feature


A Developer's Guide to Custom C++ Locales Without std::locale::combine

One of the biggest issues with std::locale::combine is that it doesn't work the way many people expect. Instead of a simple "A + B = C" merge


C++ Coroutines: Understanding and Avoiding Pitfalls with coroutine_handle

First, let's clarify what this operator does. The expression std::coroutine_handle<Promise>::operator coroutine_handle<> essentially provides a way to convert a typed coroutine handle to an untyped one


The C++ String begin() Method Explained

First, let's quickly review what std::basic_string::begin does. It's a member function of the C++ string class that returns an iterator to the first character of the string


Safe Memory Handling in C++: Beyond std::allocator

The destructor std::allocator::~allocator() is responsible for deallocating any memory that the allocator itself has acquired


Mastering C++ Concurrency: A Guide to try_lock_shared

Problem A common mistake is to repeatedly call try_lock_shared in a tight loop. This is known as polling or busy-waiting