以下代码是我为满足客户要求而尝试实现的功能的简化版。
它无法在 IBM 的 XLC 编译器(版本 9 和 11,两者)上编译,错误为 A non-type template parameter cannot have type "int X::*".
.然而,我已经用 g++ 4.7.2、clang++ 3.2 和 Intel-13.0 尝试了相同的代码,并且它们编译成功。
我很想知道 XLC 是否是这里唯一理智的声音,或者其他编译器是否正确?
struct X {
X() : y(123) {}
int y;
};
struct XFoo {
typedef int X::* Type;
};
template <typename Name, typename Name::Type value>
struct Bar {
typename Name::Type getValue(Name) {
return value;
}
};
template class Bar<XFoo, &X::y>; // xlc error here, works fine on others
int main() {}
我多次通读了 C++ 2003 标准关于模板的章节,但无法最终找到禁止使用 <type> <class>::*
的内容。作为非模板类型。我已经通过 SO 和搜索引擎搜索了解释,但没有找到任何可以帮助我做出决定的权威来源。
我知道这可能不是一个好的编码习惯,但这是客户端代码所必需的,因为他们的要求有些独特。我也尝试过其他各种替代方法,但对它们不起作用。
最佳答案
C++03 标准的第 14.1/4 节允许将指向成员的指针作为模板参数:
A non-type template-parameter shall have one of the following (optionally cv-qualified) types:
- integral or enumeration type,
- pointer to object or pointer to function,
- reference to object or reference to function,
- pointer to member.
相应地,根据 § 14.3.2/1:
A template-argument for a non-type, non-template template-parameter shall be one of:
- an integral constant-expression of integral or enumeration type; or
- the name of a non-type template-parameter; or
- the address of an object or function with external linkage, including function templates and function template-ids but excluding non-static class members, expressed as & id-expression where the & is optional if the name refers to a function or array, or if the corresponding template-parameter is a reference; or
- a pointer to member expressed as described in 5.3.1.
因此,非类型模板参数可以是指向成员的指针。有一些适用于模板特化的限制,但它们似乎不适用于这种情况。
关于c++ - 显式模板实例化在 XLC 上产生编译错误,但在其他编译器上有效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14691545/