Why can't (or won't) C++ deduce alias templates?

93 views Asked by At

It seems that C++ is either unable or unwilling to infer template arguments for template aliases of basic integer types.

Here is a relatively minimal example:

#include <stdint.h>


template<typename T>
using IntPtr = intptr_t;

template<typename T>
T* getPtr(IntPtr<T> i)
{
    return (T*) i;
}


int main()
{
    IntPtr<char> char_star = 0xcafe'babe'dead'beef;
    return *getPtr(char_star);
}

Attempting to compile the above gives the following error:

$ clang -xc++ -std=c++20 why.cc
why.cc:17:13: error: no matching function for call to 'getPtr'
    return *getPtr(char_star);
            ^~~~~~
why.cc:8:4: note: candidate template ignored: couldn't infer template argument 'T'
T* getPtr(IntPtr<T> i)
   ^
1 error generated.

I've tried with various different C++ standard versions, including c++2b, but the result was always the same.

1

There are 1 answers

0
Jan Schultke On
template<typename T>
using IntPtr = intptr_t;

T is not deducible from intptr_t, so this cannot possibly work.

IntPtr<char> is intrptr_t, so you're asking the compiler to deduce T from intrptr_t, which simply cannot be done. Aliases in C++ are weak aliases, not distinct types.

You could instead write:

template<typename T>
T* getPtr(std::intptr_t i)
{
    return reinterpret_cast<T*>(i);
}

// ...
getPtr<char>(0xcafe'babe'dead'beef);