Ere*_*ren 9 c++ template-argument-deduction c++17
我正在尝试编写一个推导指南,该指南仅从给定的构造函数参数中检测许多类型名之一,并且要求用户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>;
Run Code Online (Sandbox Code Playgroud)
上面的想法是仍然应该强迫用户输入“ int size
”模板的参数,但是“ typename T
”应该从构造函数的参数推导出来,这可能吗?
正确规范后,这就是应该如何调用方法
auto b = Board<3>(initialStateVector);
Run Code Online (Sandbox Code Playgroud)
目前,要求我这样输入;
auto b = Board<3, int>(initialStateVector);
Run Code Online (Sandbox Code Playgroud)
所以基本上,我想int
从给定推导上面的“ ” initialStateVector
,它具有类型
const vector<int>& raw_values
Run Code Online (Sandbox Code Playgroud)
上面的想法是仍然应该迫使用户输入模板的“ int size”参数,但是应该从构造函数的参数中推导出“ typename T”,这可能吗?
根据此cppreference页面中的注释(及以下示例)
仅当不存在模板参数列表时才执行类模板参数推导。如果指定了模板参数列表,则不会进行推导。
不,这是不可能的(在C ++ 17中不是;我们希望在该标准的将来版本中)。
如果您想显式显示大小并推断出类型,我能想象的最好是通过一个古老的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);
Run Code Online (Sandbox Code Playgroud)
在C ++ 11中也应该起作用。
归档时间: |
|
查看次数: |
304 次 |
最近记录: |