5

map()RubyのメソッドをC++で真似したい。戻り値の型を自動的に把握するのに苦労しています:

#include <vector>
#include <string>
#include <algorithm>
#include <iostream>

typedef std::string T2;

template<class T1,
//  class T2, // gives "couldn't deduce template parameter 'T2'"
    class UnaryPredicate>
std::vector<T2> map(std::vector<T1> in, UnaryPredicate pred)
{
    std::vector<T2> res(in.size());
    std::transform(in.begin(), in.end(), res.begin(), pred);
    return res;
}

int main()
{
    std::vector<int> v1({1,2,3});
    auto v2(map(v1, [](auto el) { return "'"+std::to_string(el+1)+"'"; }));
    std::cout << v2[0] << "," << v2[1] << "," << v2[2] << std::endl;
}

このようにコンパイルされますが、T2に固定されていstringます。他のT2定義を使用すると、コンパイラは文句を言いcouldn't deduce template parameter 'T2'ます。も使用しようとしましstd::declvalたが、おそらく正しい方法ではありません。問題を解決できませんでした。

4

2 に答える 2