错误:类型为'bar <int>&'的参数的默认参数的类型为'bar <int>'

指甲

我在编译时遇到上述错误,我该如何纠正。请帮我解决这个问题

#include <iostream>
using namespace std;

template <typename T>
class bar
{
 public:
 bar(){cout << "bar" <<"\n";}
};

template <typename T, typename ctor = bar<T>>
class foo
{
 T i;
public:
 explicit foo(ctor& c = ctor());
private:
 ctor mctor;


};

template <typename T, typename ctor>
foo<T,ctor>::foo(ctor& c):mctor(c)
{
 cout << "foo" <<"\n";
}

int main()
{
 foo<int> f;
 return 0;
}

编译:g ++ -std = c ++ 11 ctor_call.cpp

麦克风

您正在为应该在此行中通过引用传递的参数提供默认参数:

explicit foo(ctor& c = ctor());

在这里,ctor&是对type对象的引用ctor因此,该对象需要一直存在,只要您有对其的引用即可。但是默认参数将其设置为一个即将被销毁的临时对象而且由于临时对象不是标准化的,因此可以在构造函数开始之前将其销毁,因此您将一无所获。这个答案对所有这些都有很好的解释

模板使您的案例更加复杂,因此让我们更具体一些。默认ctor()是对您要引用的对象的构造函数的调用。在您的情况下,类为foo<int>,因此模板看起来像

template <int, typename ctor = bar<int>>
class foo

在这里,模板将获得第二个参数,但这是默认参数,因此您获得了ctor = bar<int>这等同于使用foo<int, bar<int>>现在,在您的函数语句中,ctor()实际上与bar<int>()-相同,它是对构造函数的调用。

一些可能的解决方案

1)不要通过默认值:

explicit foo(ctor& c);

2)不要通过引用传递:

explicit foo(ctor c = ctor());

3)通过const引用传递

explicit foo(const ctor& c = ctor());

这有点神奇,因为它const使编译器保留临时对象,直到const引用销毁为止,该常量引用在foo构造函数调用的末尾出现

4)使用foo对象外部存在的东西,例如静态或全局对象。(尽管您应该对静态保持警惕,并且我们基本上都讨厌全局变量...):

explicit foo(ctor& c = some_ctor_object_that_exists_already);

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

类型为“ int”的参数与类型为“ int *”的参数不兼容

“类型为“ int(*)()”的参数与类型为int的参数不兼容”错误?

错误:格式为'%s'的参数类型为'char *',但参数2的类型为'int'[-Wformat =]

错误无法初始化右值类型为'int'的类型为'int *'的参数

Python:获取类型为int的参数不是可重复的错误

格式'%d'期望类型为'int'的参数

警告格式指定类型为int,但参数的类型为long

使用gcc编译时出现错误:警告:格式指定类型为'int *',但参数的类型为'double *'

错误“无法将类型为“ int”的值转换为预期的参数类型为“ UInt”

格式 '%d' 需要类型为 'int' 的参数,但参数 3 的类型为 'int *'

函数具有类型为“int”的参数,但传递了类型为“int*”的参数

Binding<Int> 当预期参数类型为 'Int' SwiftUI

int[] 如何被接受为通用类型参数而不是 int?

错误消息“格式'%ld'期望类型为'long int'的参数,但是参数2具有类型'int'”

C - 格式指定类型 'int' 但参数类型为 'char *' [-Wformat]

什么是`int foo :: * bar :: *`?

预期为“ const char * __restrict__”,但参数的类型为“ int”

注意:预期为“ float *”,但参数的类型为“ int *”

注意:预期为 'char *' 但参数类型为 'int *'

警告:格式为'c'的参数类型为'int',但是参数2的类型为'char'

printf和getenv错误-预期为char *,但参数2为int类型

C ++模板:“参数的类型/值不匹配”和“预期为int的常量类型,为int”

警告:格式'%d'期望的参数类型为'int',但是参数2的类型类型为'long int'[-Wformat =]

*预期为'int *',但参数的类型为'int **'* *在c语言中为警告

警告:格式'%x'期望类型为'unsigned int'的参数

未为参数类型E,int定义运算符+

为什么函数brk()的参数为void *而不是int类型?

未为参数类型Double,int定义运算符^

没有函数模板“ max”的实例与参数列表匹配的参数类型为(int,int)