C++模板奇怪的行为:“不匹配函数”外部主干

发布于 2024-12-08 13:54:53 字数 889 浏览 1 评论 0原文

我正在使用我不太熟悉的模板,但发生了一些奇怪的事情。我有一个模板类,它继承自其他模板类。

问题是,当我在 main 方法中创建该类的实例时,它会按预期工作。但是,当我在函数内创建完全相同的实例时,它会抛出编译错误:“不匹配函数”指向模板类的构造函数。

问题是为什么它在 main 方法中工作,但在函数内却不能工作,同一段代码(包含没有问题)

代码很大,但我会尝试用一个示例来说明

int main() {
MyTemplatedClassParent<parameters> example(arguments);

MyTemplatedClassChild<parameters> example_1(arguments);
}

工作得很好。然而

int main() {
myMethod();
}

myMethod() {
MyTemplatedClassParent<parameters> example(arguments);
MyTemplatedClassChild<parameters> example_1(arguments);
}

不。基本上在第二种情况下,它无法识别调用和类的构造函数之间的匹配,并且它建议将我想要使用的类的构造函数作为候选。关键是,同样的事情在 main 方法中起作用,唯一的区别是在第二种情况下它是在方法内部声明的。

编辑:

好的,不知何故,问题出在最初默认模板的参数上。我对模板几乎一无所知,但似乎调用该方法时出现的两个实例的参数之间存在不一致。不知道如何以及为什么,但是一旦我明确指定了模板的参数,它就会编译并正常工作。再次抱歉没有提供太多信息,但我对模板的了解非常有限。

I am working with templates which I am not very familiar with but something weird is happening. I have a templated class which inherits from other templated classes.

The problem is that when I create an instance of the class in the main method it works as expected. However, when I create the very same instance inside a function then it throws compilation error: "not matching function" pointing to the constructor of the templated class.

The question is why does it work in the main method but not inside a function the very same piece of code (there is no problem with inclusion)

The code is huge but I ll try to illustrate with an example

int main() {
MyTemplatedClassParent<parameters> example(arguments);

MyTemplatedClassChild<parameters> example_1(arguments);
}

Works perfectly fine. However

int main() {
myMethod();
}

with

myMethod() {
MyTemplatedClassParent<parameters> example(arguments);
MyTemplatedClassChild<parameters> example_1(arguments);
}

does not. Basically in the second case it does not recognize the match between the call and the constructor of the class and it suggests as a candidate the constructor of the class I want to use. The point is that the very same thing works in the main method the only difference is that in the second case it is declared inside a method.

edit:

Ok, somehow the problem was on the parameters of the templates that were the default ones originally. I know almost nothing on templates, but it appears that there were inconsistencies between the parameters of the two instances that were arising when the method was called. Do not know how and why, but as soon as I specified explicitly the parameters of the templates it compiled and worked fine. Again sorry for not giving much information but my knowledge on templates is very limited.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文