成员变量中的类模板参数推导 [英] Class Template Argument Deduction in member variables

查看:89
本文介绍了成员变量中的类模板参数推导的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

扩展版本此处

我们可以创建具有默认模板参数的类模板对象,而无需键入尖括号:

We can create objects of class templates that have default template parameters without typing angle brackets:

int main()
{
    std::less a;
}

但是我们不能对成员变量执行以下操作:

But we can't do that for member variables:

struct S
{
    std::less a; // I want only type std::less<void> here
};

由于 CTAD ,但为什么编译器无法推断 std :: less< void> 在第二种情况下?也许我们不应该在那里应用CTAD,而是提供不同的机制。

It looks like the first case works due to CTAD but why can't compiler deduce std::less<void> in the second case? Maybe we shouldn't apply CTAD there but provide different mechanism.

这是否被视为标准中的错误?有解决方案吗?

Is this considered a bug in the standard? Is there a proposal to fix it?

我的用例:

我有一个提供默认值的类模板参数,例如:

I have a class template which provides default argument, like this:

template <typename T = int>
class Foo {};

template参数是一个专家功能,我本人从未使用过,但是对于那些1希望获得全面灵活性的专家百分比。现在,对于其他99%的用户,我想隐藏一个事实,即 Foo 实际上是一个类模板,但是它不起作用,因为用户必须键入 Foo<。 > 声明为成员变量时,当前的解决方案是:

The template parameter is an expert-only feature that I myself never use but it is there for those 1% of experts who want that total flexibility. Now for other 99% I want to hide the fact that Foo is actually a class template but it doesn't work because users have to type Foo<> when declaring it as a member variable, current solution is this:

template <typename T = int>
class BasicFoo {};

using Foo = BasicFoo<>;

但是它使实现代码复杂并且一点也不优雅。

But it complicates implementation code and is not elegant at all.

推荐答案

不,这不是bug。这是因为可能会有不同的构造函数调用同一个成员变量(通过类的构造函数init列表调用),从而可能得出不同的推论结果。

No, it is not a bug. It is because there could be different constructors called for the same member variable (called through class' constructor init list), potentially yielding different deduction result.

发生这种冲突时,您必须向非静态成员提供模板参数。 (静态成员不是问题,因为将有一个构造函数调用它们)

To prevent the potential for such conflict, you have to provide template arguments to non-static members. (Static members are not a problem, because there will a be a single constructor call for them)

这篇关于成员变量中的类模板参数推导的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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