c++c++17template-argument-deductionctad

How to write a partial deduction guide for class template argument deduction


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

Solution

  • 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.