5

可変個引数テンプレート パラメーターの再帰的な性質と特定のテンプレートのインスタンス化を使用して、パラメーター リストを 1 つずつ「食べる」という基本的な概念を理解しています。

ラムダは、特定の型を取り、特定の型を返すように記述できることを理解しています。私はまだ C++14 と C++11 を学んでいるので、どちらかをマスターしていないことに注意してください。

他の スタックオーバーフローの質問を見た後の私の試みは次のとおりです。

// For std::string
#include <string>

// For std::cout
#include <iostream>


//Create a generalized list instantiation
template <typename ... F>
struct overload : public F... {
    overload(F... f) : F(f)... {}
};      

//Create an specific end-case, where we directly
//inherit the () operator in order to inherit
//multiple () overloads
template <typename F>
struct overload : F {
    using F::operator();
};


//template function to create an overload
template <class... F>
auto make_overload(F... f) {
    return (f...);
}

int main() {
    auto f = [](int x,int y) -> int {
        return x+y;
    };
    auto g = [](double x,double y) -> int {
        return std::ftoi(x+y);
    };
    auto h = [](std::string x,std::string y) -> int {
        return std::stoi(x+y);
    };

    //Ah, but this is a function.
    auto fgh = make_overload(f,g,h);

    std::cout << (fgh(1,2)) << std::endl;
    std::cout << (fgh(1.5,2.5)) << std::endl;
    std::cout << (fgh("bob","larry")) << std::endl;
}

コリル: http://coliru.stacked-crooked.com/a/5df2919ccf9e99a6

ここで概念的に欠けているものは何ですか? 他の答えはこの問題を額面通りに簡潔に答えるかもしれませんが、答えが私の考えを逃れる理由の説明を探しています。演算子を継承する必要があることを理解しusing F::operator()、戻り値とパラメーターの型が異なることを正しく述べた場合、これを機能させるために他に何をする必要がありますか?

ここに私の考えがあります:

  1. 一般的な可変個引数テンプレートの基本クラスを作成します。
  2. 特定のテンプレート ケースを作成して、特定のラムダの をオーバーロードしoperator()ます。
  3. 可変個引数のテンプレート引数リストを受け取るヘルパー関数を作成し、それを使用して「オーバーロード」クラスを構築します。
  4. タイプが明確であることを確認してください。
4

1 に答える 1

5

あなたは実際には再帰しませんでした。

// primary template; not defined.
template <class... F> struct overload;

// recursive case; inherit from the first and overload<rest...>
template<class F1, class... F>
struct overload<F1, F...> : F1, overload<F...> {
    overload(F1 f1, F... f) : F1(f1), overload<F...>(f...) {}

    // bring all operator()s from the bases into the derived class
    using F1::operator();
    using overload<F...>::operator();
};      

// Base case of recursion
template <class F>
struct overload<F> : F {
    overload(F f) : F(f) {}
    using F::operator();
};
于 2015-05-18T06:32:13.103 に答える