How to specify template deduction guides for template aliases?

Viewed 399

I am trying to make this code compile in VS 2019 (16.10.4) with /std:c++17. The following fails:

namespace my
{
   template<class _Key, class _Compare = std::less<_Key>, class _Allocator = std::allocator<_Key>>
   using Set = std::set<_Key, _Compare, _Allocator>;
}

void test()
{
    std::set set1 = { 1, 2, 3 };
    static_assert(std::is_same_v<std::set<int>, decltype(set1)>);

    my::Set set2 = { 1, 2, 3 }; // Error here.
    static_assert(std::is_same_v<my::Set<int>, decltype(set2)>);
}

with error:

error C2955: 'my::Set': use of alias template requires template argument list
message : see declaration of 'my::Set'

The same code compiles fine on godbolt with gcc -std=c++17 without any deduction guides. See sample.

Is there a way to make this compile on VS 2019 (16.10.4) with /std:c++17? My actual code is quite verbose. I created this minimal reproducible sample and it might just come down to solving this small piece. I also tried specifying deduction guides for my::Set but they have similar errors.

1 Answers

my::Set in your code is an alias template, and class template argument deduction for alias templates is a new feature of C++20: https://en.cppreference.com/w/cpp/compiler_support/20

Experimentally one can find that template argument deduction in this example is available in Visual Studio since version 16.11, please also specify /std:c++20 command-line option. Demo: https://gcc.godbolt.org/z/93jdvfPcn

The same code compiles fine on godbolt with gcc -std=c++17 without any deduction guides.

It is a bug in GCC that it allows class template argument deduction for alias templates in C++17 mode: https://gcc.gnu.org/bugzilla/show_bug.cgi?id=103852

Related