![](/img/trans.png)
[英]not getting expected ambiguity on template specialization and overloading c++
[英]C++ Template Metaprogramming Specialization Ambiguity
所以我只是从模板元编程开始,我一直在写一个字符串类。 我实现了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> { ... }
如何解决这种歧义?
谢谢。
在这里,你定义一个Substring
与0
, 0
任何class S
:
template <class S>
struct Substring<0, 0, S> {
typedef Null substr;
};
在这里,您可以使用I
, L
和String< C, S >
定义Substring
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
更好I, L
但比String< C, S >
更差。 如果您将第一种情况声明为:
template <char C, class S>
struct Substring<0, 0, String< C, S > > {
typedef Null substr;
};
这样,它将比其他任何方式都更加专业。 但是,您的代码可能还有其他歧义。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.