March 14th, 2024

How well does ATL CComPtr support class template argument deduction (CTAD)?

Continuing our investigation of which C++ COM wrappers support class template argument deduction (CTAD), next up is ATL’s CComPtr.

ATL’s CComPtr works with CTAD right out of the box because the constructor that takes a pointer provides all the information needed to specialize the template class.

template <class T>
class CComPtr : public CComPtrBase<T>
{
public:
    CComPtr(_Inout_opt_ T* lp); // this constructor

    ⟦ other stuff ⟧
};

void sample(Test* p)
{
    // Works right out of the box!
    auto smart = CComPtr(p);
}

The compiler sees that the constructor parameter is a T*, so it can figure out what T needs to be.

Interestingly, but perhaps not surprisingly, it is the smart pointer class with the most straightforward constructor that works best with CTAD. CTAD tries to enable magic template arguments, and if you make your constructor too fancy, CTAD won’t be able to figure out what it needs to do.

Next up is WRL, and things get more complicated.

Topics
Code

Author

Raymond has been involved in the evolution of Windows for more than 30 years. In 2003, he began a Web site known as The Old New Thing which has grown in popularity far beyond his wildest imagination, a development which still gives him the heebie-jeebies. The Web site spawned a book, coincidentally also titled The Old New Thing (Addison Wesley 2007). He occasionally appears on the Windows Dev Docs Twitter account to tell stories which convey no useful information.

1 comment

Discussion is closed. Login to edit/delete existing comments.

  • Neil Rashbrook

    The smart pointer class that I’m used to is also only templated on the base type of the raw pointer, so I imagine it would work with CTAD despite predating it.