私が達成しようとしているのは、さまざまなファンクターを引数として取ることができるファンクターを作成することです。
編集:私の問題の理由、「最も厄介な解析」、および解決策がよく説明されています:この質問と回答、最も厄介な解析タグ全体、およびウィキペディアのページを参照してください。それでも、質問する前に問題を特定できませんでした。他の人に役立つかもしれないので、この質問は残しておきます。
私がしたこと:
ヘッダー ファイル内functor.hpp
:
#ifndef FUNCTOR_HPP
#define FUNCTOR_HPP
#include <functional>
template <typename T, typename BinOp = typename std::plus<T>>
struct doer {
BinOp op;
doer(BinOp o = std::plus<T>()) : op(o) {}
T operator()(const T& a, const T& b) const
{ return op(a, b); }
};
#endif // FUNCTOR_HPP
このヘッダーを使用すると、次のfunctor.cpp
ようなプログラムを作成できます。
#include <iostream>
#include "functor.hpp"
int main()
{
doer<int> f;
std::cout << f(3, 7) << std::endl;
}
コンパイルして実行すると、期待どおりに取得できます。
$ make functor
g++ -std=c++14 -pedantic -Wall functor.cpp -o functor
$ ./functor
10
$
doer
別の演算子 ( ではない) でmy をインスタンス化する方法を見つけるのに苦労していますstd::plus<T>
。
doer<int, std::multiplies<int>> f2(std::multiplies<int>());
これは問題なくコンパイルされf2(3, 7)
ますが、積 21 を取得するために を呼び出す方法を見つけることができませんでした。たとえば、プログラムに別の行を追加すると:
int r = f2(3, 7);
コンパイルしようとすると、次のようになります。
$ make functor
g++ -std=c++14 -pedantic -Wall functor.cpp -o functor
functor.cpp: In function ‘int main()’:
functor.cpp:10:20: error: invalid conversion from ‘int’ to ‘std::multiplies<int> (*)()’ [-fpermissive]
int r = f2(3, 7);
^
functor.cpp:10:20: error: too many arguments to function ‘doer<int, std::multiplies<int> > f2(std::multiplies<int> (*)())’
functor.cpp:9:37: note: declared here
doer<int, std::multiplies<int>> f2(std::multiplies<int>());
^
functor.cpp:10:20: error: cannot convert ‘doer<int, std::multiplies<int> >’ to ‘int’ in initialization
int r = f2(3, 7);
^
何が起こっている?どういうf2(3, 7)
わけかオーバーロードされたものを呼び出していないようoperator()
です...