是否可以在专用模板类中访问非类型模板参数的值?
-
18-09-2019 - |
题
是否可以在专用模板类中访问非类型模板参数的值?
如果我有具有专业化的模板类:
template <int major, int minor> struct A {
void f() { cout << major << endl; }
}
template <> struct A<4,0> {
void f() { cout << ??? << endl; }
}
我知道以上情况是简单的硬码值4和0,而不是使用变量,但是我拥有的较大的类是我专门的,我希望能够访问该值。
<4,0>是否有可能访问 major
和 minor
值(4和0)?还是我必须将它们分配给模板实例化作为常数:
template <> struct A<4,0> {
static const int major = 4;
static const int minor = 0;
...
}
解决方案
可以通过拥有一组“特征”结构来解决此类问题。
// A default Traits class has no information
template<class T> struct Traits
{
};
// A convenient way to get the Traits of the type of a given value without
// having to explicitly write out the type
template<typename T> Traits<T> GetTraits(const T&)
{
return Traits<T>();
}
template <int major, int minor> struct A
{
void f()
{
cout << major << endl;
}
};
// Specialisation of the traits for any A<int, int>
template<int N1, int N2> struct Traits<A<N1, N2> >
{
enum { major = N1, minor = N2 };
};
template <> struct A<4,0>
{
void f()
{
cout << GetTraits(*this).major << endl;
}
};
其他提示
并不是对您的问题的答案,但是您可以枚举它们,即:
enum{
specialisationMajor=4,
specialisationMinor=0
};
template <> struct A<specialisationMajor,specialisationMinor> {
static const int major = specialisationMajor;
static const int minor = specialisationMinor;
...
}
并不是对您的问题的答案,但是下面的想法对我有所帮助:
#include <iostream>
template <int major, int minor, int= major, int= minor> struct A {
void f() { std::cout << major << '\n'; }
};
template <int major, int minor> struct A<major, minor, 4, 0> {
void f() { std::cout << major << ':' << minor << '\n'; }
};
int main()
{
A<3, 3>().f();
A<4, 0>().f();
}
不,您无法访问专用的非类型模板参数。但是,这是一种不重复自己的方法 f
:
template <int major, int minor>
struct f_impl
{
void f() { cout << major << endl; }
};
template <int major, int minor>
struct A : public f_impl<major, minor>
{};
template <> struct A<4,0> : public f_impl<4,0>
{};
在此示例中,一个人并没有得到太多的收益,因为一个人需要写 4,0
两次( - 所以您可以在 cout
在您的操作中)。但是,如果您使用模板参数具有更多功能,则开始支付。
不隶属于 StackOverflow