为什么编译器调用默认构造函数

Why is the compiler calling the default constructor?

本文关键字:构造函数 默认 调用 编译器 为什么      更新时间:2023-10-16

为什么我收到下面的错误?(为什么编译器要调用默认构造函数?)

#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);