我正在尝试在“perpendicular()”函数中使用模板参数推导:
#include <iostream>
template <typename component = double>
struct offset {
component x;
component y;
};
template <typename component>
offset(component x, component y) -> offset<component>;
template <typename component>
offset<component> perpendicular(offset<component> const &o) {
return offset{o.y, -o.x};
}
template <typename component>
std::ostream &operator<<(std::ostream &s, offset<component> const &o) {
return s << '(' << o.x << ", " << o.y << ')';
}
int main() {
std::cout << perpendicular({3.1, 1.2}) << '\n';
return 0;
}
然而,这段代码无法编译;Clang(使用-std='c++17'
)会提示:candidate template ignored: couldn't infer template argument 'component' offset<component> perpendicular(offset<component> const &o) {
。
我应该写成perpendicular(offset{1.0, 2.0})
还是有其他方法可以给编译器一个提示呢?
{ ... }
用于初始化offset
,然后将其传递给perpendicular
,即offset x = {3.0, 2.1}; perpendicular(x)
(这个方法可行)。我还发现在模板参数中添加默认值 (template <typename component = double>
) 可以使其编译通过。 - user11589013template <typename T = double> offset<T> perpendicular(offset<T>)
,在对perpendicular({42, 51})
进行推导时,由于不会发生推导,您将获得double
而不是期望的int
。 - Jarod42perpendicular({3.12, 1.34})
时,编译器是不是会找一个perpendicular(initializer_list<double>)
而不是perpendicular(offset{initializer_list<double>})
? 即使没有其他的重载函数,我仍然不确定为什么会发生这种情况。 - user11589013template <typename T> perpendicular(offset<T>)
,而您没有提供offset
,因此无法推断出T
(它不会尝试offset{args}
)。 - Jarod42