Why do I receive the error below? (Why is the compiler trying to call the default constructor?)
#include <cmath>
template<typename F> struct Foo { Foo(F) { } };
int main()
{
Foo<double(double)>(sin); // no appropriate default constructor available
}
It is because there is no difference between
Foo<double(double)>(sin);
and
Foo<double(double)> sin;
Both declare a variable of name sin
.
The parens are superfluous. You can put as many parens as you want.
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
All are same!
If you want to create temporary instance of the class, passing sin
as argument to the constructor, then do this:
#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
}
Output:
called
called
called
Demo : http://ideone.com/IjFUe
They work, because all three syntaxes force them to be expressions, rather than variable declarations.
However, if you try this (as @fefe sugguested in the comment):
Foo<double(double)>(&sin); //declaration, expression
It is not going to work, for it declares a reference variable, and since it is not initialized, you will get compilation error. See : http://ideone.com/HNt2Z