C++17 部分推导指南

C++17 Partial Deduction Guide

我正在尝试编写一个推导指南,它只检测给定构造函数参数中的许多类型名之一,并要求用户手动输入 int size

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>;

上面的想法是,用户仍然应该强制输入模板的参数“int size”,但是“typename T”应该从构造函数的参数中推导出来,这可能吗?

正确指定后,应该这样调用方法

auto b = Board<3>(initialStateVector);

目前要求我这样输入;

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

所以基本上,我希望从给定的 initialStateVector 推导出上面的“int”,其类型为

const vector<int>& raw_values

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?

根据 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.

不,这是不可能的(在 C++17 中不行;我们希望在标准的未来版本中)。

如果你想要显式大小并推断类型,我能想象的最好的方法是通过 good-old make_something 函数。

我的意思如下(使用 std::size_t 作为大小,如 std::array 和几乎所有的 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);

这应该也适用于 C++11。

我想出了一个使用大小提示对象的解决方法

template<int size>
struct SizeHint {};

您的 class 会将此作为附加的构造函数参数:

Board(SizeHint<size>, const std::vector<T>& raw_values)

你这样调用构造函数:

auto b = Board(SizeHint<2>{}, v);

奖金

这种方法也适用于类型提示(我找到这个帖子的最初动机):

template<typename T>
struct TypeHint{};

template<typename Result, typename T>
struct S {
    S(TypeHint<Result>, T arg) : t{arg}{}
    Result r() {return t;}
    T t;
};

#include <iostream>
int main() {
    S s{TypeHint<int>{}, 5.7};
    std::cout << s.r() << std::endl;
}

这也可以与可变参数模板结合使用:

template<typename Result, typename... Args>
struct S {
    S(TypeHint<Result>, Args... args) : t{args...}{}
    std::tuple<Args...> t;
};