为什么编译器调用默认构造函数
Why is the compiler calling the default constructor?
为什么我收到下面的错误?(为什么编译器要调用默认构造函数?)
#include <cmath>
template<typename F> struct Foo { Foo(F) { } };
int main()
{
Foo<double(double)>(sin); // no appropriate default constructor available
}
这是因为
Foo<double(double)>(sin);
和
Foo<double(double)> sin;
都声明了一个名为sin
的变量
父节点是多余的。
int x; //declares a variable of name x
int (x); //declares a variable of name x
int ((x)); //declares a variable of name x
int (((x))); //declares a variable of name x
int (((((x))))); //declares a variable of name x
都是一样的!
如果您想创建类的临时实例,将sin
作为参数传递给构造函数,然后这样做:
#include<iostream>
#include <cmath>
template<typename F>
struct Foo { Foo(F) { std::cout << "called" << std::endl; } };
int main()
{
(void)Foo<double(double)>(sin); //expression, not declaration
(Foo<double(double)>(sin)); //expression, not declaration
(Foo<double(double)>)(sin); //expression, not declaration
}
输出:called
called
called
Demo: http://ideone.com/IjFUe
可以工作,因为所有三种语法都强制它们是表达式,而不是变量声明。
然而,如果你尝试这样做(就像@fefe在评论中建议的那样):
Foo<double(double)>(&sin); //declaration, expression
它不会工作,因为它声明了一个引用变量,并且由于它没有初始化,您将得到编译错误。参见:http://ideone.com/HNt2Z
我想你正在尝试从函数指针类型制作模板。不知道double(double)是什么意思,但如果你真的想引用函数指针类型,你应该这样做:
Foo<double(*)(double)> SinFoo(sin);
相关文章:
- 为什么在没有显式默认构造函数的情况下,将另一个结构封装在联合中作为成员的结构不能编译
- 初始化具有非默认构造函数的std::数组项的更好方法
- 具有默认模板类型的默认构造函数的类型推导
- 如何使用非默认构造函数实例化模板化类
- 为什么不调用移动构造函数?(默认情况下只有构造器,没有别的)
- 有没有一种代码密度较低的方法来使用非默认构造函数初始化数组?
- 声明没有默认构造函数的字段
- 基类中的默认析构函数禁用子类中的移动构造函数(如果有成员)
- 没有默认构造函数作为模板参数的自定义比较器
- C++17 没有默认构造函数的地图放置(私有默认构造函数)
- 使用移动调用对等构造函数unique_ptr默认构造函数
- C++复制构造函数和默认构造函数
- 将向量从 N1 缩小到 N2 项,而不触发默认构造函数并仅使用 move 语义
- 构造函数默认公共和私有变量
- 类模板构造函数默认参数
- 构造函数默认参数
- C++模板构造函数默认参数
- 在c++中设置构造函数默认值
- c++构造函数默认参数
- C++构造函数默认值头文件