c++模板元编程专门化歧义

C++ Template Metaprogramming Specialization Ambiguity

本文关键字:专门化 歧义 编程 c++      更新时间:2023-10-16

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

如何解决这个歧义?

谢谢。

这里您定义了Substring0, 0和任何class S:

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

这里你定义了一个Substring, I, LString< 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;
};

那么这将比任何其他的都更专门化。但是,在您的代码中可能存在其他的歧义来源。