另一个类范围内的类模板参数类型推导

问题描述

我在使用简单的类模板时遇到类型推导指南问题,这是在主函数范围内的实例化问题,但是在另一个类中却没有做到。

这里是一个例子:

template<class T>
struct X
{
    X(T&)
    {
    }
};

struct User
{
    X x{1}; // error: invalid use of template-name 'X' without an argument list
};

int main()
{
    int i;
    auto x = X(i); // OK
    (void)x;
}

我有点困惑,为什么要这样以及如何解决。 有什么想法吗?

解决方法

Clangd给出了更有意义的错误消息,这可能会使您(或我,或其他人)更容易在网络上搜索答案,

Use of class template 'X' requires template arguments;
argument deduction not allowed in non-static struct member

here对此进行了很好的解释。