2015-11-11 23 views
6

私は次のコードをコンパイルしようとしている:可変個引数テンプレートとCアレイ

template <typename T, int N> void foo(const T (&array)[N]) {} 

template <typename T> static int args_fwd_(T const &t) { foo(t); return 0; } 

template<class ...Us> void mycall(Us... args) { 
    int xs[] = { args_fwd_(args)... }; 
} 

int main(void) { 
    int b[4]; 
    mycall(b); 
} 

mycall関数は、各引数に機能fooを呼び出すためにargs_fwd_関数に転送し、その後可変引数テンプレートを使用して。

これはほとんどの引数型で正しく動作します(fooの関数を適切に定義したと仮定します)。しかし、私はCスタイルの配列(int b[4])を渡そうとするとポインタに変わり、配列(ポインタではない)を必要とするテンプレート化されたfoo関数を見つけることができません。 gcc 4.9.3のエラーは次のとおりです。

error: no matching function for call to ‘foo(int* const&)’ 
note: candidate is: 
note: template<class T, int N> void foo(const T (&)[N]) 
    template <typename T, int N> void foo(const T (&array)[N]) {} 
note: template argument deduction/substitution failed: 
note: mismatched types ‘const T [N]’ and ‘int* const’ 

ポインタを探している部分に注意してください。これはclangでも同じですが、これは標準に準拠しているようです。これがポインタに変換されずにC配列であることを保持する方法はありますか?

+0

このような配列型のテンプレートでは、次のことに留意してください。使用する配列のサイズごとに個別のインスタンスがあります。あなたがプログラムに持っている大きさの異なる配列の数に応じて、膨大な量の膨満を意味するかもしれません。 –

答えて

6

はい。完璧な転送を使用:

#include <utility> 

template<class ...Us> void mycall(Us&&... args) { 
    int xs[] = { args_fwd_(std::forward<Us>(args))... }; 
} 
+1

パーフェクト、ありがとう! – JoshG79

関連する問題