我试图弄清楚如何让编译器根据传递给构造函数的参数推断模板参数。这是我尝试过的:
#include <array>
template<size_t N, size_t M>
class A {
public:
A(const std::array<float, N>& n, const std::array<double, M>& m)
: nElements(n), mElements(m) {
}
private:
std::array<float, N> nElements;
std::array<double, M> mElements;
};
int main() {
A<2, 3> a({1.4f, 2.5f}, {3.0, 2.1, 4.8});
// ^
// |
// how can i avoid <2,3> expclicit declaration here?
}
Run Code Online (Sandbox Code Playgroud)
非常感谢您提供任何可能的帮助!
正如@Thomas 的回答所说,在 c++17 之前,您无法从构造函数参数中推断出类模板参数。
但是在这种情况下提供推导指南将不起作用,正如评论中指出的那样,因为 std::array 的模板参数不能从大括号初始化列表中推导出来。
我们可以通过创建一个推导指南来回避这个问题,其中参数是原始数组。这解决了这个问题,因为原始数组的大小可以从大括号初始化列表中推导出来。
// deduce the size using raw arrays
template<size_t N, size_t M>
A(float const (&)[N], double const (&)[M]) -> A<N,M>;
int main() {
A a({1.4f, 2.5f}, {3.0, 2.1, 4.8}); // yay
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
85 次 |
| 最近记录: |