gpt4 book ai didi

c++ - 为什么 Visual Studio 无法在模板类中选择正确的构造函数?

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:17:54 25 4
gpt4 key购买 nike

当我实例化模板类时,Visual Studio 看不到正确的构造函数。我哪里做错了?

我已经尝试过明确/删除复制/移动构造函数。没有帮助。

#include <set>

using namespace std;

template <class T, template<class> class ConnectionType>
struct node
{
T value;
node(const T& value) : value(value) {}

set<ConnectionType<T>> connections;
};

template <class T>
struct connection
{
node<T, connection>* n;

connection(node<T, connection>* n) :
n(n) {}

bool operator<(const connection& b) const
{
return n < b.n;
}
};

int main()
{
node<int, connection> a(0);
connection<int> c(&a); // ERROR HERE

return 0;
}

错误:

error C2664:  'connection<T>::connection(connection<T> &&)': cannot convert argument 1 from 'node<int, connection> *' to 'node<T, connection<T>> *'

最佳答案

好像是VS的bug。 VS 似乎正在处理 injected class name connection作为相当于 connection<T> 的类型名称, 但它应该被视为类模板本身的模板名称,即 connectionnode<T, connection>* n;connection(node<T, connection>* n) ,因为 node 的第二个模板参数是模板模板参数。

(强调我的)

In the following cases, the injected-class-name is treated as a template-name of the class template itself:

  • it is followed by <
  • it is used as a template argument that corresponds to a template template parameter
  • it is the final identifier in the elaborated class specifier of a friend class template declaration.

Otherwise, it is treated as a type-name, and is equivalent to the template-name followed by the template-parameters of the class template enclosed in <>.

template <template <class, class> class> struct A;

template<class T1, class T2>
struct X {
X<T1, T2>* p; // OK, X is treated as a template-name
using a = A<X>; // OK, X is treated as a template-name
template<class U1, class U2>
friend class X; // OK, X is treated as a template-name
X* q; // OK, X is treated as a type-name, equivalent to X<T1, T2>
};

PS:您的代码可以很好地编译 clang .

PS: 处理为connection<T>bool operator<(const connection& b) const .

关于c++ - 为什么 Visual Studio 无法在模板类中选择正确的构造函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57310666/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com