2

だから私はテンプレートのメタプログラミングを始めたばかりで、文字列クラスを書いています。テンプレート関連の問題があまりなく、ToString、Concat、CharAt、Length を実装しました。次のように Substring を実装しようとしていました。

struct Null;

// String class definition
template <char C, class S>
struct String {
  static const char chr = C;
  typedef S tail;
};

// Substring
// Gets the substring of length L starting at index I from string S.
template <int I, int L, class S>
struct Substring;

template <class S>
struct Substring<0, 0, S> {
  typedef Null substr;
};

// Will also cover I < 0 case
template <int I, int L>
struct Substring<I, L, Null> {
  typedef Null substr;
};

template <int L, char C, class S>
struct Substring<0, L, String<C, S> > {
  typedef String<C, typename Substring<0, L-1, S>::substr> substr;
};

template <int I, int L, char C, class S>
struct Substring<I, L, String<C, S> > {
  typedef typename Substring<I-1, L, S>::substr substr;
};

int main() {
  // This all works...
  typedef String<'H', String<'e', String<'l', String<'l',
            String<'o', Null> > > > > hello;
  typedef String<',', String<' ', Null> > comma;
  typedef String<'w', String<'o', String<'r', String<'l', String<'d',
            String<'!', Null> > > > > > world;
  typedef Concat<hello, Concat<comma, world>::newstr>::newstr hello_world;
  // ...up to here.
  typedef Substring<3, 5, hello_world>::substr mystr;
  return 0;
}

コンパイルすると、あいまいなエラーが発生します。

template.cpp:161: error: ambiguous class template instantiation for ‘struct
    Substring<0, 0, String<'o', String<'r', String<'l', String<'d', String<'!',
    Null> > > > > >’
template.cpp:149: error: candidates are: struct Substring<0, 0, S>
template.cpp:160: error:                 struct Substring<0, L, String<C, S> >
template.cpp:165: error:                 struct Substring<I, L, String<C, S> >
template.cpp:161: error: invalid use of incomplete type ‘struct Substring<0, 0, 
    String<'o', String<'r', String<'l', String<'d', String<'!', Null> > > > > >’
template.cpp:146: error: declaration of ‘struct Substring<0, 0, String<'o',
    String<'r', String<'l', String<'d', String<'!', Null> > > > > >’
template.cpp: In function ‘int main()’:
template.cpp:197: error: template argument 1 is invalid

私は少し混乱しています。テンプレートの特殊化の要点は、このようなことを行うことだと思いました。これは、次のようなものの単なる拡張ではないのはなぜですか。

template <int N>
struct Foo { ... }

template <>
struct Foo<0> { ... }

このあいまいさを修正するにはどうすればよいですか?

ありがとう。

4

1 に答える 1

6

Substringここで、 with 00および anyを定義しますclass S

template <class S>
struct Substring<0, 0, S> {
  typedef Null substr;
};

Substringここで、 with ILおよび aを定義しますString< C, S >

template <int I, int L, char C, class S>
struct Substring<I, L, String<C, S> > {
  typedef typename Substring<I-1, L, S>::substr substr;
};

一方は によく一致しますI, Lが、 には一致しませんString< C, S >。最初のケースを次のように宣言するとします。

template <char C, class S>
struct Substring<0, 0, String< C, S > > {
  typedef Null substr;
};

そうすれば、これは他のものよりも専門的になります。ただし、コードには他にもあいまいさの原因がある場合があります。

于 2011-10-27T23:10:22.320 に答える