2017-07-13 5 views
2

1)テンプレートファンクタN回を実行し、2)結果を累積するバリアブルテンプレートまたは定数式を書きたいと思います。私はテンプレートファンクタに実行される関数を動かすと実際にコンパイルに失敗する小さなサンプルを書きました。私は解決策に近いと感じていますが、多分私は間違っています。コンパイルの問題を伴う単純な(再帰的)バリデーションテンプレート "accumulate_for"関数

#include <iostream> 
#include <string> 

struct F { 
    template <int id> 
    static int run(int val) { 
     return id * val; 
    } 
}; 

template<unsigned int n> 
struct accumulate_for 
{ 
    template <class Funct> 
    static int get(int val) { 
     return 
     (
     accumulate_for<n-1>::get(val) 
     + 
     Funct::run<n>(val) 
     ); 
    } 
}; 

template<> 
struct accumulate_for<0> 
{ 
    template <class Funct> 
    static int get(int val) { 
     return 0; 
    } 
}; 

int main() 
{ 
    std::cout << accumulate_for<3>::get<F>(1) << std::endl; 
} 
+0

を参照してください[STDと代替:: index_sequence](http://coliru.stacked-crooked.com/ a/a994dfd1a8890ef) – Jarod42

答えて

5
  1. accumulate_for<n>::getメンバ関数テンプレートであるので、あなたはそれを呼び出すときにテンプレート引数を指定する必要があります。

  2. getrun(どちらも依存名)がテンプレートであることを示すには、template keywordを使用する必要があります。

templateキーワードの使用方法についての詳細情報については

template<unsigned int n> 
struct accumulate_for 
{ 
    template <class Funct> 
    static int get(int val) { 
     return 
     (
     accumulate_for<n-1>::template get<Funct>(val) 
     //     ~~~~~~~~ ~~~~~~~ 
     + 
     Funct::template run<n>(val) 
     //  ~~~~~~~~ 
     ); 
    } 
}; 

LIVE

Where and why do I have to put the “template” and “typename” keywords?

+0

テンプレートキーワードが必要な理由はわかりません。コンパイラはこれを見るべきですか? – dgrat

+1

@dgratリンクを確認しましたか?要するに、 'get 'の場合、コンパイラは 'get'をテンプレート名とみなさず、' <'はより小さい記号として解析されます。一方、 'accumulate_for'(例えば、' accumulate_for <99> '?)のいくつかの指定があるかもしれません。静的データメンバは' get'となり、 'accumulate_for :: get songyuanyao