以下のエラーが表示されるのはなぜですか?(コンパイラがデフォルトのコンストラクタを呼び出そうとするのはなぜですか?)
#include <cmath>
template<typename F> struct Foo { Foo(F) { } };
int main()
{
Foo<double(double)>(sin); // no appropriate default constructor available
}
以下のエラーが表示されるのはなぜですか?(コンパイラがデフォルトのコンストラクタを呼び出そうとするのはなぜですか?)
#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を置くことができます。
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
3つの構文すべてが、変数宣言ではなく式になるように強制するため、これらは機能します。
ただし、これを試してみると(@fefeがコメントで示唆しているように):
Foo<double(double)>(&sin); //declaration, expression
参照変数を宣言し、初期化されていないため、コンパイルエラーが発生するため、機能しません。参照: http: //ideone.com/HNt2Z
関数ポインタ型からテンプレートを作成しようとしていると思います。double(double)の意味はわかりませんが、関数ポインタ型を本当に参照したい場合は、次のようにする必要があります。
Foo<double(*)(double)> SinFoo(sin);