Nic*_*ick 2 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;
}
Run Code Online (Sandbox Code Playgroud)
当我编译时,我得到一个模糊错误:
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
Run Code Online (Sandbox Code Playgroud)
我有点困惑.我认为模板专业化的重点是做这样的事情.为什么这不仅仅是以下内容的扩展:
template <int N>
struct Foo { ... }
template <>
struct Foo<0> { ... }
Run Code Online (Sandbox Code Playgroud)
我该如何解决这种歧义?
谢谢.
在这里你定义一个Substringwith 0,0以及任何class S:
template <class S>
struct Substring<0, 0, S> {
typedef Null substr;
};
Run Code Online (Sandbox Code Playgroud)
在这里,你定义一个Substring与I,L和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;
};
Run Code Online (Sandbox Code Playgroud)
没有人比其他人更好,因为一个是更好的匹配,I, L但更糟糕的匹配String< C, S >.如果您要将第一个案例声明为:
template <char C, class S>
struct Substring<0, 0, String< C, S > > {
typedef Null substr;
};
Run Code Online (Sandbox Code Playgroud)
那么这将比任何其他更专业.但是,您的代码可能存在其他歧义来源.