使用支撑初始化程序列表时,模板参数推导失败 [英] Template argument deduction fails when using braced initializer list

查看:59
本文介绍了使用支撑初始化程序列表时,模板参数推导失败的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在'perpendicular()'函数中使用模板参数推导:

I'm trying to use template argument deduction in the 'perpendicular()' function:

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

但是,它不能编译;叮当声(带有 -std ='c ++ 17')说:候选模板被忽略:无法推断模板参数'component'offset< component>Vertical(offset< component> const& o){.

This however doesn't compile; Clang (with -std='c++17') says: candidate template ignored: couldn't infer template argument 'component' offset<component> perpendicular(offset<component> const &o) {.

我应该辞职写 perpendicular(offset {1.0,2.0})还是有办法给编译器一个提示?

Should I resign to writing perpendicular(offset{1.0, 2.0}) or is there a way to give the compiler a hint?

推荐答案

带有 {/*..*/} 的问题是它没有类型,并且大多数只能推导为 std :: initializer_list< T> T [N] .

Issue with {/*..*/} is that it has no type, and can mostly only be deduced as std::initializer_list<T> or T[N].

因此,下面将允许所需的语法:

So following would allow desired syntax:

template <typename component>
offset<component> perpendicular(component const (&o)[2]) {
    return offset{o[1], -o[0]};
    // return perpendicular(offset{o[0], o[1]});
}

演示

这篇关于使用支撑初始化程序列表时,模板参数推导失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆