Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Partial class template argument deduction in C++17

In the example below, we use the C++17 feature "Class template argument deduction" to deduce that val is of type Base<int, double, bool>:

template<class T, class U, class V>
struct Base {
    Base(T, U) { };
    Base(T, U, V) { };
    Base(V) { };
};

void func() {
    Base val(1, 4., false);
}

Now, is it possible to partially specify the template arguments, and let the remaining ones be deduced? Effectively something like this:

Base<V = bool> val1(1, 4.);        // U & V deduced --> Base<int, double, bool>
Base<T = bool, T = int> val2(5.);  // V deduced     --> Base<bool, int, double>

I've tried e.g.

template<class T, class U> using Base2 = Base<T, U, double>;

void func() {
    NewBase2 val(1, 2);
}

but it doesn't compile: 'Base2': use of alias template requires template argument list.

Is partial deduction possible somehow? If it is not possible directly, are there any good workarounds?

like image 755
Phil-ZXX Avatar asked Aug 19 '19 20:08

Phil-ZXX


People also ask

What is template argument deduction?

Template argument deduction is used in declarations of functions, when deducing the meaning of the auto specifier in the function's return type, from the return statement.

What is template argument in C++?

A template parameter is a special kind of parameter that can be used to pass a type as argument: just like regular function parameters can be used to pass values to a function, template parameters allow to pass also types to a function.

What is a deduction guide?

Template deduction guides are patterns associated with a template class that tell the compiler how to translate a set of constructor arguments (and their types) into template parameters for the class. The simplest example is that of std::vector and its constructor that takes an iterator pair.


1 Answers

CTAD (Class Template Argument Deduction) is an all or nothing process currently. You either specify nothing and allow the compiler to deduce all of the arguments, or you specify all of the arguments taking the compiler out of the loop.

There is a paper (P1021R0) which asks for this and more, but it has not yet been accepted. There was a paper asking for partial specialization but after revisions it has been removed. The newest revision still includes a proposal to have CTAD function when using an alias.


Per @Barry Support for Alias templates (P1814) and Aggregates (P1816) have been added to the working draft for C++20. No support for partial CTAD or CTAD with inherited constructors has been added.

like image 66
NathanOliver Avatar answered Sep 18 '22 12:09

NathanOliver