[英]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
的变量。
parens是多余的。 您可以根据需要添加任意数量的parens。
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
演示: http : //ideone.com/IjFUe
它们起作用,因为所有三种语法都强制它们是表达式,而不是变量声明。
但是,如果你试试这个(如评论中的@fefe sugguested):
Foo<double(double)>(&sin); //declaration, expression
它不会起作用,因为它声明了一个引用变量,并且因为它没有被初始化,所以你会得到编译错误。 请参阅: http : //ideone.com/HNt2Z
我想你正试图从函数指针类型中创建一个模板。 不知道什么是double(double)意思,但是如果你真的想引用函数指针类型那就是你应该做的:
Foo<double(*)(double)> SinFoo(sin);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.