0

JavaにPredicateクラスのC/C++同等の構造/クラスはありますか?

具体的には、以下に示すような非常に単純な Java コードがあります。

import java.util.function.Predicate;
public class JavaPredicates {
    public static void main(String[] args) {
        Predicate<String> i  = (s)-> s.equals("ABCD");
        Predicate<String> j  = (s)-> s.equals("EFGH");
        Predicate<String> k  = (s)-> s.equals("IJKL");
        Predicate<String> l  = (s)-> s.equals("MNOP");
        Predicate<String> m  = (s)-> s.equals("QRST");
        Predicate<String> n  = (s)-> s.equals("UVWYZ");

        System.out.println(i.or(j).or(k).or(l).or(m).or(n).test("ABCD"));
    }
}

同じプログラムを C または C++ で実装したいと考えています。これを行うためのデフォルトの方法または外部ライブラリはありますか?

4

3 に答える 3

4

C++ には、使用している Java コンストラクトに非常に似ているように見えるラムダがあります。

auto i = [](string const & s){return s == "ABCD";}

組み込みのチェーンはありませんが、概念は似ています-インライン定義関数です。C++ ロジック コンストラクトを使用して、ラムダを任意のコンストラクトに結合できます。ラムダを使用してそれを行うこともできます。

auto final_check = [i,j,k,l,m,n](string const & s){return i(s) || j(s) || k(s).....};
于 2016-10-12T01:04:46.617 に答える
2

簡略化された構文はauto lambdaName=[ <capture> ] ( <params> ) -> <ret> { body }

  • [<capture>]final vars or effectively finalsは、ラムダによってキャプチャされたJava のリストです。final
  • (<params>)ラムダのパラメーターのリストです
  • ret- 戻り値の型 - コンパイラが戻り値の型を推測できるほどラムダが単純な場合はオプション
  • { body }-自明

C++11 ラムダ関数の構文に関する完全な説明

あなたの場合:

auto i = [/* no capture */]
          (const std::string& s) // params
          // no ret type spec: simple enough, the compiler will deduce it
          { return s=="ABCD"; }
;
// calling it is just as simple as
std::string str="xyz";
// no more i.test(str), you just call it as a function
bool res0 = i(str); // will be false


const char* charStr="mnp";
bool res1 = i(charStr); // the compiler knows the charStr can be converted
                        // to std::string and will generate the code
                        // for this conversion.
于 2016-10-12T01:18:25.327 に答える