【发布时间】:2009-09-24 09:33:31
【问题描述】:
这是我的问题:在标题中我定义了一个结构模板type_to_string,它旨在定义一个与给定类型参数对应的字符串:
namespace foo {
template <typename T>
struct type_to_string
{
static const char * value;
};
}
template <typename T>
const char * foo::type_to_string<T>::value = "???";
我还为字符串定义了一个默认值。
现在,我想使用宏来定义新类型:
#define CREATE_ID(name) \
struct name; \
\
template<> \
const char * foo::type_to_string<name>::value = #name;
问题是我希望宏可以在命名空间中使用,例如:
namespace bar
{
CREATE_ID(baz)
}
这是不可能的,因为type_to_string<T>::value 必须定义在包含foo 的命名空间中。
这是我得到的编译错误:
[COMEAU 4.3.10.1] error: member "foo::type_to_string<T>::value [with T=bar::baz]"
cannot be specialized in the current scope
[VISUAL C++ 2008] error C2888: 'const char *foo::type_to_string<T>::value' :
symbol cannot be defined within namespace 'bar'
with
[
T=bar::baz
]
奇怪的是,GCC 4.3.5(MinGW 版本)不会产生任何错误。
有没有人知道解决方法,可能是通过使用一些我不知道的查找规则(即在宏中声明 type_to_string 以便每个命名空间都有自己的版本,或类似的东西)?
【问题讨论】:
标签: c++ templates namespaces