2017-08-24 4 views
0

私はこのバリデーショナルテンプレートで長時間戦っています。誰でも私を助けてくれますか?私は、cmath関数を呼び出してすべてのパラメータをベクトルで渡すことができる実行プログラムを構築したいと考えています。次のコードを考えてみてください:atan2は2を取るながら関数内のC++のあいまいさは、引数がベクトルで渡されています

bool execute(const std::string &functionName, const std::vector<double> &params) 
{ 
    if (functionName == "cos") return execute(cos, params); 
    if (functionName == "atan2") return execute(atan2, params); 
    return false; 
} 

機能cos、1つのパラメータを取ります。呼び出しがあいまいなので、doublefloatの両方のために働くcos

  1. 機能:しかし、私は2つの問題に遭遇

    template <typename... Types> 
    bool execute(double (*func)(Types...), const std::vector<double> &params) 
    { 
        if (params.size() != sizeof...(Types)) { 
         errorString = "Wrong number of function arguments"; 
         return false; 
        } 
    
        errno = 0; 
        result = func(params[0]); 
        errorString = strerror(errno); 
        return !errno; 
    } 
    

    :私はこのような何かを持っていると思いました。また、typenameの代わりにdoubleを使用して強制的に使用することはできません。それとも別の方法がありますか?

  2. 私は関数funcをコールしようとしていますが、どのように関数の型に応じてベクトルから適切な量の引数を指定できますか?

多分私が知りませんが既にC + +で利用可能なものがありますか? :) どうもありがとう!

+1

あなたは明らかにのみ1と2のパラメータを持つ関数を処理する必要があるので、それは1つが ''ダブル(* FUNC)(ダブル)を取り、他の 'ダブル(二非テンプレートオーバーロードを書くことが最も簡単でしょう* func)(ダブル、ダブル) ' –

+0

@IgorTandetnik、ありがとう。それが今私が実際にやっていることです。テンプレートを使ってコードの量を減らしたかっただけです。しかし、それがどうしても可能かどうかはわかりません。 –

+0

可能ですが、実際にはコードの量を減らすことはできません。それは確かにそれをはるかに複雑にします。 –

答えて

1

あなたは、std::index_sequenceを使用するようなものかもしれません:

template <typename... Types, std::size_t ... Is> 
double execute(double (*func)(Types...), 
       const std::vector<double> &params, 
       std::index_sequence<Is...>) 
{ 
    if (params.size() != sizeof...(Types)) { 
     throw std::runtime_error("Wrong number of function arguments"); 
    } 
    return func(params[Is]...); 
} 

template <typename... Types> 
double execute(double (*func)(Types...), const std::vector<double> &params) 
{ 
    return execute(func, params, std::index_sequence_for<Types...>()); 
} 

と(過負荷を修正するためのテンプレート引数を指定する)と呼んでいます。

double execute(const std::string &functionName, const std::vector<double> &params) 
{ 
    if (functionName == "cos") return (execute<double>)(cos, params); 
    if (functionName == "atan2") return (execute<double, double>)(atan2, params); 
    throw std::runtime_error("Unknown function name"); 
} 
関連する問題