【发布时间】:2011-10-27 04:06:57
【问题描述】:
我刚开始使用模板元编程,所以我只是尝试做一些基本的事情。我得到了适用于 BST 的 Size 和 Lookup “方法”,所以我决定尝试制作一个 String 类。我在 cpp 文件中有这段代码:
#include <iostream>
#include <string>
using namespace std;
struct Null;
// String
template <char C, typename S>
struct String {
static const char chr = C;
typedef S tail;
};
// ToString
template <typename S>
struct ToString;
template <char C, typename S>
struct ToString<String<C, S> > {
static const string str;
};
template <char C, typename S>
const string ToString<String<C, S> >::str = C + ToString<S>::str; // (*)
template <char C>
struct ToString<String<C, Null> > {
static const string str;
};
template <char C>
const string ToString<String<C, Null> >::str = C + ""; // to make it a string
int main() {
typedef String<'H', String<'e', String<'l', String<'l',
String<'o', Null> > > > > myString;
cout << ToString<myString>::str << endl;
return 0;
}
当我运行这段代码时,它会输出“地狱”。在基本情况下我做错了什么?它似乎与“”有关,因为我曾经在(*) 上将C + ToString<S>::str 作为"" + C + ToString<S>::str,然后输出是随机垃圾。
【问题讨论】:
-
@post that's gone: 我不知道,这只是一个练习模板元编程的感觉。假设 Concat、CharAt、ToString 和 Length。
-
当我运行这段代码时,它会输出“地狱”。这听起来像是有人在对你玩万圣节恶作剧 =)
-
你可以使用可变参数模板吗?
-
您是否尝试过与
typedef String<'o', Null> myString;合作开始,然后沿着链条向上发展? -
@Dani 我也在考虑使用可变参数模板的方法。它可能会降低嵌套级别。
标签: c++ templates metaprogramming