gpt4 book ai didi

c++ - 在模板化构造函数中调用构造函数时的有趣行为

转载 作者:太空宇宙 更新时间:2023-11-04 14:48:22 25 4
gpt4 key购买 nike

当我遇到一个我无法追踪的有趣的编译器错误时,我刚刚创建了一个我认为我可以立即完成的非常小的项目(它是关于基本委托(delegate)的)。这是代码的简化版本:

class NoComp {
};

class Comp {
bool operator==(const Comp& other)
{ std::cout << "Working!" << std::endl; return true;}
};

struct Test {
template<typename T>
Test(T&& obj) {}
bool operator==(const Test& other);
};
int main()
{
Test a(Comp());
Test b(NoComp());
a.operator ==(b);
}

当使用 g++ version 4.8.3 20140911 (Red Hat 4.8.3-7) (GCC) found here 编译时,这会产生以下编译器错误:

main.cpp: In function 'int main()':                                    
main.cpp:22:13: error: request for member 'operator==' in 'a', which is
of non-class type 'Test(Comp (*)())'
a.operator ==(b);

我无法弄清楚该错误的含义以及它存在的原因。那里发生了什么,是错误还是标准涵盖?如果可以,我该如何避免?

最佳答案

Test a(Comp());
Test b(NoComp());

这声明了两个名为ab 的函数。第一个有一个 Comp(*)() 类型的参数和 Test 的返回类型,第二个有一个 NoComp(*)() 并且还返回一个 TestComp() 是函数类型,作为函数类型的所有参数,调整为指向函数的指针类型。 NoComp() 也是如此。

使用双括号:

Test a((Comp()));
Test b((NoComp()));

或从 C++11 开始的列表初始化。

关于c++ - 在模板化构造函数中调用构造函数时的有趣行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28055471/

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