类模板参数依赖于构造函数
使用模板化数字包装结构:
template <int I> struct Num { static const int n = I; };
和一些重载函数:
template <typename T>
Num<0> id(T x) { return Num<0>(); }
Num<1> id(int x) { return Num<1>(); }
Num<2> id(double x) { return Num<2>(); }
Num<3> id(char x) { return Num<3>(); }
我可以使用 decltype
和类型来初始化 Zod
结构的 m_i
成员id
的返回参数:
template <typename T>
struct Zod {
Zod(T x) { m_i = identity<decltype(id(x))>::type::n; }
int m_i;
};
但是,我真正想要的是 Zod
结构有第二个整数模板参数初始化为 m_i< /code> 设置为。
template <typename T, int I = ?>
struct Zod { ... }
这似乎是可能的,因为 identity
/decltype
表达式计算结果为编译时常量;例如,这在全局范围内没有问题:
char c;
static const int g = identity<decltype(id(c))>::type::n;
问题是构造函数的 x 参数在 Zod 模板声明的范围内不可用。能做到吗?
With a templated number wrapping struct:
template <int I> struct Num { static const int n = I; };
and a few overloaded functions:
template <typename T>
Num<0> id(T x) { return Num<0>(); }
Num<1> id(int x) { return Num<1>(); }
Num<2> id(double x) { return Num<2>(); }
Num<3> id(char x) { return Num<3>(); }
I can initialise the m_i
member of a Zod
struct using decltype
and the type of the return argument of id
:
template <typename T>
struct Zod {
Zod(T x) { m_i = identity<decltype(id(x))>::type::n; }
int m_i;
};
However, what I'd really like is for the Zod
struct to have a second integer template argument initialised to the value which m_i
was set to.
template <typename T, int I = ?>
struct Zod { ... }
This seems possible, as the identity
/decltype
expression evaluates to a compile time constant; for example, this is fine at global scope:
char c;
static const int g = identity<decltype(id(c))>::type::n;
The problem is that the x
argument of the constructor is not available in the scope of Zod
's template declaration. Can it be done?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这是完全可能的——只需传入
*((T*)nullptr)
即可获取任何类型 T 的左值,无论其可构造性如何。毕竟,您实际上对构造函数参数所做的就是将其传递给 id ,然后传递给 decltype ,这在模板中是完全可行的,因为您知道x
是T
。It's perfectly possible- just pass in
*((T*)nullptr)
to obtain an lvalue of any type T regardless of it's constructability. After all, all you actually do with the constructor argument is pass it toid
and thendecltype
that, which is perfectly doable in the template, since you know that the type ofx
isT
.