Search code examples
c++templatesboostc++20

class template argument deduction for template alias of an alias (C++20)


I am using boost::outcome_v2::result with a custom type for the error and an alias to this type.

Now I am struggling to get class template argument deduction to work for my alias.

The code:

class my_error{ ... };

template <typename result_t>
using my_result = boost::outcome_v2::result<result_t, my_error>;

The issue is that when I return this type from a function I can't use class template argument deduction for the result type:

const my_result res = some_function();

But it works if I use boost::outcome_v2::result directly:

const boost::outcome_v2::result res = some_function();

Is there a way to write a deduction guide for my alias so that it can work as well?

Compiler Explorer link


Solution

  • Is there a way to write a deduction guide for my alias so that it can work as well?

    No, as alias templates are just an alias for a type, it is by design not allowed to write explicit deduction guide specifically for an alias template.

    Rather, this is an inherent and known limitation of CTAD, as highlighted in P1021R6 ([Core] Filling holes in Class Template Argument Deduction)

    Class Template Argument Deduction for alias templates

    While Class Template Argument Deduction makes type inferencing easier when constructing classes, it doesn't work for type aliases, penalizing the use of type aliases and creating unnecessary inconsistency.

    [...]

    Finally, in the spirit of alias templates being simply an alias for the type, we do not propose allowing the programmer to write explicit deduction guides specifically for an alias template.

    P1814R0 (Wording for Class Template Argument Deduction for Alias Templates) broke out the alias template parts of P1021, and was accepted by CWG in 2019, but Clang has not yet implemented it and GCC doesn't even list its status towards the paper.

    Note however that in your case, result is also an alias template, so you are actually not comparing CTAD for alias templates vs a non-alias template. Clang, for example, rejects both cases.