SFINAE 尝试使用 bool 会给出编译器错误:“template argument ‘T::value”涉及模板参数”
我尝试使用 bool
实现 SFINAE(与流行的 void_
技巧):
template<typename T, bool = true>
struct Resolve
{
static const bool value = false;
};
template<typename T>
struct Resolve<T, T::my_value>
{
static const bool value = true;
};
目标是专门化内部定义有 static const bool my_value = true;
的类。如果它们被定义为 false
或未定义,则不要对其进行专门化。即
struct B1 { // specialize Resolve for this case
static const bool my_value = true;
};
struct B2 { // don't specialize
static const bool my_value = false;
};
struct B3 {}; // don't specialize
当在 B1
上应用上述技巧时,它会给出编译错误:
Resolve<B1>::value;
错误:模板参数“T::my_value”涉及模板参数
我知道这可以通过其他方式来实现。但是,我有兴趣知道为什么它会在这里给出编译器错误以及它可以在这段代码本身中解决吗?
I tried to implement an SFINAE using bool
(unlike popular void_
trick):
template<typename T, bool = true>
struct Resolve
{
static const bool value = false;
};
template<typename T>
struct Resolve<T, T::my_value>
{
static const bool value = true;
};
The goal is to specialize, the classes which have static const bool my_value = true;
defined inside it. If they are defined false
or not defined then don't specialize it. i.e.
struct B1 { // specialize Resolve for this case
static const bool my_value = true;
};
struct B2 { // don't specialize
static const bool my_value = false;
};
struct B3 {}; // don't specialize
When applying the above trick on B1
it gives the compilation error:
Resolve<B1>::value;
error: template argument ‘T::my_value’ involves template parameter(s)
I am aware that this can be achieved with alternate ways. However, I am interested in knowing, why it gives compiler error here and can it be solved in this code itself ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
实际上,第 §14.5.4/9 节禁止你所做的事情,其中说:
技巧可以是使用类型作为第二个模板参数,封装非类型值,如下所述:
现在它编译罚款。
Actually what you're doing is forbidden by section §14.5.4/9 which says,
The trick could be using a type for second template parameter as well, encapsulating the non-type value, as described below:
Now it compile fines.