リスト内の最大数を決定するためにそれ自体を呼び出す可変個引数テンプレート関数があります (テンプレート化された引数によって構成されます)。パラメータ パックが空の場合に特殊化しようとしているので、リストの先頭にある番号を返すことができますが、その方法がわかりません。可変個引数テンプレートとテンプレートの特殊化に慣れてきたばかりですが、これまでのところ次のとおりです。
#include <string>
#include <iostream>
using namespace std;
template <int N, int... N2>
int tmax() {
return N > tmax<N2...>() ? N : tmax<N2...>();
}
template <int N>
int tmax() {
return N;
}
int main() {
cout << tmax<32, 43, 54, 12, 23, 34>();
}
ただし、これにより次のエラーが発生します。
test.cpp: In function ‘int tmax() [with int N = 34, int ...N2 = {}]’:
test.cpp:9:45: instantiated from ‘int tmax() [with int N = 23, int ...N2 = {34}]’
test.cpp:9:45: instantiated from ‘int tmax() [with int N = 12, int ...N2 = {23, 34}]’
test.cpp:9:45: instantiated from ‘int tmax() [with int N = 54, int ...N2 = {12, 23, 34}]’
test.cpp:9:45: instantiated from ‘int tmax() [with int N = 43, int ...N2 = {54, 12, 23, 34}]’
test.cpp:9:45: instantiated from ‘int tmax() [with int N = 32, int ...N2 = {43, 54, 12, 23, 34}]’
test.cpp:18:39: instantiated from here
test.cpp:9:45: error: no matching function for call to ‘tmax()’
test.cpp:9:45: error: no matching function for call to ‘tmax()’
私もこれを試してみましたが、それが機能するかどうかを確認するためです (ただし、0 未満の数値を返すことができないように、リストに数値 0 をランダムに導入します)。
template <int N, int... N2>
int tmax() {
return N > tmax<N2...>() ? N : tmax<N2...>();
}
template <>
int tmax<>() {
return 0;
}
ただし、上記のエラーに加えて、次のエラーが発生します。
error: template-id ‘tmax<>’ for ‘int tmax()’ does not match any template declaration
では、これを機能させるにはどうすればよいですか?
-std=c++0x
フラグ付きで g++ 4.5.2 を使用しています。