SFINAE尝试使用bool给出编译器错误:“模板参数'T :: value'涉及模板参数” [英] SFINAE tried with bool gives compiler error: "template argument ‘T::value’ involves template parameter"

查看:245
本文介绍了SFINAE尝试使用bool给出编译器错误:“模板参数'T :: value'涉及模板参数”的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试使用 bool 实现SFINAE(不像流​​行的 void _ trick ):

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;
  };

目标是专门化,类 static const bool my_value = true; 里面定义。如果它们被定义 false 或没有定义,那么不专门化它。也就是

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



当在 B1 它给出编译错误:

When applying the above trick on B1 it gives the compilation error:

Resolve<B1>::value;




错误:模板参数'T :: my_value'涉及模板参数s)

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 ?

推荐答案

你正在做的是禁止的部分§14.5.4/ 9说,

Actually what you're doing is forbidden by section §14.5.4/9 which says,


部分专用非类型参数除非参数表达式是简单标识符,否则表达式不应涉及部分专门化的模板参数。

诀窍可能是使用类型用于第二个模板参数, -type 值,如下所示:

The trick could be using a type for second template parameter as well, encapsulating the non-type value, as described below:

template<bool b> struct booltype {};

template<typename T, typename B = booltype<true> >
struct Resolve
{
  static const bool value = false;
};

template<typename T>
struct Resolve<T, booltype<T::my_value> >
{
  static const bool value = true;
};

现在编译罚款

这篇关于SFINAE尝试使用bool给出编译器错误:“模板参数'T :: value'涉及模板参数”的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆