C ++模板元编程专业化歧义

时间:2011-10-27 23:05:55

标签: c++ templates metaprogramming template-specialization template-meta-programming

所以我刚刚开始使用模板元编程,我一直在编写一个字符串类。我实现了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> { ... }

如何解决这种歧义?

感谢。

1 个答案:

答案 0 :(得分:6)

您可以在此处使用Substring0和任何0定义class S

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

您可以在此处使用SubstringIL来定义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;
};

然后这将比任何其他更专业。但是,您的代码可能存在其他歧义来源。

相关问题