gpt4 book ai didi

C++ 模板元编程特化歧义

转载 作者:搜寻专家 更新时间:2023-10-31 00:19:34 26 4
gpt4 key购买 nike

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

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

没有人比另一个更好,因为一个人更适合 I, L但对 String< C, S > 的匹配更差.如果您要将第一个案例声明为:

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

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

关于C++ 模板元编程特化歧义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7923454/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com