当相同的约束必须推断出不同的类型时,为什么将概念放入类型说明符中会导致类型推导失败? [英] Why does putting concept to type specifier fail type deduction when the same constraint must deduce different types?

查看:100
本文介绍了当相同的约束必须推断出不同的类型时,为什么将概念放入类型说明符中会导致类型推导失败?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们有:

template <typename ...T> concept bool Numerics = ( std::is_arithmetic_v<T> && ... ) ;
template <typename T>    concept bool Numeric  =   std::is_arithmetic_v<T>;

然后,我们让编译器推导出所有数字:

Then we let compiler deduce all the numbers:

template <typename T, typename U, typename V, typename W> requires Numerics<T,U,V,W>
auto foo(T arg1, U arg2, V arg3, W arg4) {
    return 0.0 + arg1 + arg2 + arg3 + arg4;
}

std::cout << foo (1,2.0,3.0f,4.0l) << "\n";

编译器推导出所有期望的参数类型:

Compiler deduces all argument types like expected:

auto foo<int, double, float, long double>(int, double, float, long double):

当我们尝试将约束分配到类型说明符中以编写较短的版本时:

When we try distribute constraints into type specifier for writing a shorter version:

auto foo2(Numeric arg1, Numeric arg2, Numeric arg3, Numeric arg4) {
    return 0.0 + arg1 + arg2 + arg3 + arg4;
}

尽管如此,编译器出人意料地未能推断出这一点:

Though, compiler surprisingly fails to deduce this:

// err: deduction fails
//
// std::cout << foo2(1,2,3,4.0) << "\n"; 

似乎编译器尝试将所有类型推论为相同的类型,在这里必须失败.

It seems compiler try deduce all into the same type, which must fails here.

为什么?编译器不应该能够从同一个约束推论出不同的类型吗?

Why? Shouldn't compiler be able to deduce different types from the same contraint?

实时

推荐答案

这是Concepts TS最具争议的方面之一.当你说

This is one of the more controversial aspects of the Concepts TS. When you say

template <typename T> concept bool C = true;

template <C T, C U>
void func(T t, U u);

这就像你说的那样翻译

template <typename T, typename U> requires (C<T> && C<U>)
void func(T t, U u);

但是,当您使用缩写语法"说

However, when you use the "abbreviated syntax" to say

void func(C t, C u); 

这就像你说的那样翻译

template <typename T> requires C<T>
void func(T t, T u);

许多人认为这是违反直觉的,并且存在建议进行更改.但是,其他人(包括Bjarne Stroustrup本人)也赞成一致扣除"-参见Stroustrup的论文

Many people consider this to be counterintuitive, and there has been a proposal to change it. However, others (including Bjarne Stroustrup himself) are in favour of "consistent deduction" -- see Stroustrup's paper here.

在撰写本文时,合并到C ++ 20草案中的Concepts TS的子集不包含缩写语法.目前尚不清楚它是否会在20年前结束,如果是的话,它将使用哪种扣除方式-这些论点仍有待解决.

At the time of writing, the subset of the Concepts TS incorporated into the C++20 draft does not include the abbreviated syntax. It's not clear at the moment whether it will end up in '20, and if so, what sort of deduction it will use -- the arguments are still to be resolved.

这篇关于当相同的约束必须推断出不同的类型时,为什么将概念放入类型说明符中会导致类型推导失败?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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