详细的请求是MAKE这样一个包含这样一个类模板和一堆特殊化(部分或全部)的头文件,也可能包含它们的几个成员函数。然后,只要开发人员没有修改头文件本身,那么她/他就没有机会在头文件中对她/他自己的类模板进行专门化。
以下是一个示例: 头文件'MyIncl.h'中的内容:
namespace n1
{
template < typename _Ty >
class MyTmplCls
{
typedef MyType1 OutputType;
};
template <>
class MyTmplCls< MyType4Spec >
{
typedef MyType2 OutputType;
};
}
然后有人可以在他自己的来源中做到这一点:
...
namespace n1
{
template <>
class MyTmplCls< YourType >
{
typedef YourSelfDefType1 OutputType;
};
}
...
这是我想要防止的。
请注意,问题是如何制作SUCH CLASS TEMPLATE(当然还包含头文件),而不是“如何防止修改头文件”或“如何防止类模板被专门化”由其用户无需修改头文件本身'。简单来说,关键是标题文件不是“没有被修改”,而是“被谁修改”,而后者的答案只是“标题制造者”。
这是我到目前为止所尝试的: 头文件'MyIncl.h'中的内容:
struct n1
{
template < typename _Ty, DummyType >
class MyTmplCls
{
typedef MyType1 OutputType;
};
template < DummyType _dt >
class MyTmplCls< MyType4Spec, _dt >
{
typedef MyType2 OutputType;
};
};
我认为只要您的项目包含MyIncl.h,就无法重新定义结构。 但有人仍然可以在他的来源中做到这一点:
...
template < DummyType _dt >
class n1::MyTmplCls< YourType, _dt >
{
typedef YourSelfDefType1 OutputType;
};
...
我找到了另一种方式:
template < DummyType >
struct n1
{
template < typename _Ty, DummyType >
class MyTmplCls
{
typedef MyType1 OutputType;
};
template < DummyType _dt >
class MyTmplCls< MyType4Spec, _dt >
{
typedef MyType2 OutputType;
};
};
它比以前的方式更受限制,尽管有人仍然可以这样做:
...
template <>
template < DummyType _dt >
class n1<0>::MyTmplCls< YourType, _dt >
{
typedef YourSelfDefType1 OutputType;
};
...
上面的代码部分只是试图告诉我打算做什么。他们不一定是正确的方式。 好的......现在我需要真正的正确方法。任何有用的提示将不胜感激。
** 如果您想自己测试一下,上面代码需要 * < / EM>
typedef int MyType4Spec;
typedef long MyType1;
typedef short MyType2;
typedef int DummyType;
属于头文件,
typedef void YourType;
typedef void YourSelfDefType1;
属于“您的”来源。
答案 0 :(得分:2)
为什么会出现偏执狂 - 如果程序员愿意,任何事情都可能被破坏!?
因此,答案是:没有办法。