Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++17 Partial Deduction Guide

I am trying to write a deduction guide, that only detects one of many typename's from given constructor argument and requires user to enter int size manually

template <int size, typename T>
struct Board
{
            array<array<T, size>, size> values;

            explicit Board(const vector<T>& raw_values){

            }
};
template <int size, typename T> Board(const vector<T>&) -> Board<int size, T>;

The idea above is that user should still be forced to enter "int size" argument of template, but "typename T" should be deduced from the argument of constructor, is this possible?

After correct specification, this is how method should be called

auto b = Board<3>(initialStateVector);

Currently, it requires to me to enter like this;

auto b = Board<3, int>(initialStateVector);

So basically, I want "int" above to be deduced from given initialStateVector, which has type

const vector<int>& raw_values
like image 749
Eren Avatar asked May 28 '19 23:05

Eren


People also ask

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.

What is template argument deduction in C++?

Class Template Argument Deduction (CTAD) is a C++17 Core Language feature that reduces code verbosity. C++17's Standard Library also supports CTAD, so after upgrading your toolset, you can take advantage of this new feature when using STL types like std::pair and std::vector.


1 Answers

The idea above is that user should still be forced to enter "int size" argument of template, but "typename T" should be deduced from the argument of constructor, is this possible?

According a note (and following examples) in this cppreference page

Class template argument deduction is only performed if no template argument list is present. If a template argument list is specified, deduction does not take place.

no, this isn't possible (not in C++17; we can hope in future versions of the standard).

If you want explicit the size and let deduce the type, the best I can imagine is pass through a good-old make_something function.

I mean something as follows (using std::size_t for the size, as in std::array and almost all STL)

template <std::size_t S, typename T>
Board<S, T> make_Board (std::vector<T> const & v)
 { return {v}; }

// ...

auto b = make_Board<3>(initialStateVector);

that should works also in C++11.

like image 175
max66 Avatar answered Sep 30 '22 20:09

max66