SFINAE 会干扰偏序吗?

如何解决SFINAE 会干扰偏序吗?

我正在开发一个使用名为 PETE 的非常古老的 C++ 表达式模板 (ET) 引擎的库。 (我试图找到它的源代码的链接,以便我可以引用它,但我只找到了关于它的文章。)

快速概览:通过 ET,C++ 编译器使用运算符中缀形式(+、-、*、/)从表达式构建一个表示表达式及其操作的 C++ 类型。 PETE 方法的核心是 ForEach 类模板,用于稍后解析和评估表达式。

我想要做的是提供一个专门的 ForEach,当它的参数满足特定条件时会被使用。我正在尝试使用部分专业化和使用 enable_if,但编译器抱怨“不明确的部分专业化”。

如果需要,我很乐意发布代码的其他部分,但我会坚持使用有问题的直接类模板(注意:我添加了 Enable 参数以使以后的专业化可以选择enable_if。NB2:为了更简短的帖子,我不包括该方法的实现):

template<class Expr,class FTag,class CTag,class Enable = void>
struct ForEach
{
  typedef typename LeafFunctor<Expr,FTag>::Type_t Type_t;
  inline static
  Type_t apply(const Expr &expr,const FTag &f,const CTag &)
  {
    // empty
  }
};

然后是第一个部分专业化(也是标准 PETE 的一部分)。这就是后来称为数字“1”的内容:

// 1
template<class Op,class A,class B,class CTag>
struct ForEach<BinaryNode<Op,A,B>,FTag,CTag >
{
  typedef typename ForEach<A,CTag>::Type_t TypeA_t;
  typedef typename ForEach<B,CTag>::Type_t TypeB_t;
  typedef typename Combine2<TypeA_t,TypeB_t,Op,CTag>::Type_t Type_t;
  inline static
  Type_t apply(const BinaryNode<Op,B> &expr,const CTag &c) 
  {
    // default implementation for BinaryNode
  }
};

这里是我额外的部分专业化,编译器抱怨。它实际上抱怨数字“2”与数字“1”不明确:

// A
template<class A,class CTag>
struct ForEach<BinaryNode<OpMultiply,ViewSpinLeaf,CTag,enable_if_t< ! EvalToSpinMatrix<A>::value > >
{
  typedef typename ForEach<A,OpMultiply,CTag>::Type_t Type_t;
  inline static
  Type_t apply(const BinaryNode<OpMultiply,const ViewSpinLeaf &f,const CTag &c)
  {
    // default implementation for BinaryNode (this is the same as above)
  }
};


// 2
template<class A,enable_if_t< EvalToSpinMatrix<A>::value > >
{
  typedef typename ForEach<A,CTag>::Type_t Type_t;

  inline static
  Type_t apply(const BinaryNode<OpMultiply,const CTag &c) 
  {
    // special implementation for when EvalToSpinMatrix<A>::value is true 
  }
};

编译器错误如下(注意:我重新格式化以增强可读性)

  ambiguous template instantiation for ‘struct ForEach<BinaryNode<OpMultiply,Vector<double>,Vector<double> >,OpCombine,void>’

  candidate '1':
    candidates are: template<class Op,class CTag> struct ForEach<BinaryNode<Op,CTag> ;
Op = OpMultiply;
A = Vector<double>;
B = Vector<double>;
FTag = ViewSpinLeaf;
CTag = OpCombine;

  candidate '2':
note:   template<class A,class CTag> struct ForEach<BinaryNode<OpMultiply,T1,T2>,typename std::enable_if<EvalToSpinMatrix<A>::value,void>::type>;
A = Vector<double>;
B = Vector<double>;
CTag = OpCombine;

据我所知,该标准适用了所谓的“部分排序”,即如果一个部分专业化至少与另一个专业化一样专业,但不是相反,则它比另一个专业化更专业。应用到这个例子这说:

数字 2 至少与数字 1 一样专业,因为对于每个参数集(对于数字 2),我可以找到匹配的集合(对于数字 1)。但是数字 1 至少不像数字 2 那样专业。如果我将 FTag 设置为除 ViewSpinLeaf 之外的任何内容,那么数字 2 无法匹配。因此,数字 2 更加专业化。所以,我不明白为什么编译器不这么看。

作为第二个测试,我删除了专业化“A”(具有负 enable_if 的那个)并从专业化“2”中删除了 enable_if_t 位。这编译得很好,这意味着数字“2”中的所有其他语句/typedef 都可以工作。但是,这不是我需要的,因为此代码路径适用于所有 BinaryNode<OpMultiply,..> 而不仅仅是特定情况。

以防万一。我在 Ubuntu 上使用的编译器是 g++ 9.3,启用了标准的 C++14。

编辑:正如评论中所建议的,BinaryNode<Op,..>BinaryNode<OpMultiply,..> 之间可能存在歧义。我将数字“2”更改为以下内容:

// 2
template<class Op,const CTag &c) 
  {
  }
  
  inline static
  Type_t apply(const BinaryNode<Op,const CTag &c)
  {
  }
};

现在只有 FTag 更专业。编译器抱怨同样的歧义:

note: candidates are: ‘template<class Op,CTag>;
Op = OpMultiply;
A = Vector<double>;
B = Vector<double>;
FTag = ViewSpinLeaf;
CTag = OpCombine;

‘template<class Op,void>::type>;
Op = OpMultiply;
A = Vector<double>;
B = Vector<double>;
CTag = OpCombine;

数字“2”显然更专业。

EDIT2:添加一个最小的复制器。有一个 #if 0 ,如果这样保留,程序将编译并采用默认代码路径。但是,当使用 #if 1 打开部分特化时,会重现歧义。

#include<type_traits>
#include<iostream>

using namespace std;


template<class T>        class Vector {};

struct ViewSpinLeaf {};
struct OpCombine {};

template<class LeafType,class LeafTag> struct LeafFunctor {};
template<class A,class Op,class Tag> struct Combine2 {};


template<class T1,class T2,class Op>
struct BinaryReturn {
  typedef T1 Type_t;
};


template<class T>
struct LeafFunctor<Vector<T>,ViewSpinLeaf>
{
  typedef T Type_t;
  inline static
  Type_t apply(const Vector<T> & s,const ViewSpinLeaf& v)
  {
    return Type_t();
  }
};


template<class A,class Op>
struct Combine2<A,B,OpCombine>
{
  typedef typename BinaryReturn<A,Op>::Type_t Type_t;
  inline static
  Type_t combine(const A& a,const B& b,const Op& op,const OpCombine& do_not_use)
  {
    return op(a,b);
  }
};

struct OpMultiply
{
  template<class T1,class T2>
  inline typename BinaryReturn<T1,T2,OpMultiply >::Type_t
  operator()(const T1 &a,const T2 &b) const
  {
    return (a * b);
  }
};


template<class Op,class Left,class Right>
class BinaryNode
{
public:
  BinaryNode(const Op &o,const Left &l,const Right &r) : op_m(o),left_m(l),right_m(r) {}

private:
  Op    op_m;
  Left  left_m;
  Right right_m;
};





template<class Expr,class Enable = void >
struct ForEach
{
  typedef typename LeafFunctor<Expr,const CTag &)
  {
    return LeafFunctor<Expr,FTag>::apply(expr,f);
  }
};



template<class Expr,class CTag>
inline typename ForEach<Expr,CTag>::Type_t
forEach(const Expr &e,const CTag &c)
{
  return ForEach<Expr,CTag>::apply(e,f,c);
}


template<class Op,const CTag &c) 
  {
    std::cout << "I don't want to be here. " << std::endl;
    return Type_t();
  }
};






#if 0

template<class A>
struct EvalToSpinMatrix
{
  constexpr static bool value = false;
};

template<>
struct EvalToSpinMatrix<Vector<double> >
{
  constexpr static bool value = true;
};



template<class A,const CTag &c) 
  {
    std::cout << "I want to get here. " << std::endl;
    return Type_t();
  }
};
#endif



int main(int argc,char **argv)
{
  OpMultiply op;
  Vector<double> left;
  Vector<double> right;

  BinaryNode< OpMultiply,Vector<double> > rhs(op,left,right);
  
  forEach( rhs,ViewSpinLeaf(),OpCombine() );
}

我应该说根据 enable_if 特征选择带有 EvalToSpinMatrix 开关的部分特化很重要。显然,在实际应用中,这个特性更加复杂。很好,它重现了这个简单版本中的歧义。

解决方法

过了一段时间我我有了答案。

首先,我将代码简化到最低限度,通过砍掉任何不需要重现错误的东西。这一切都归结为为什么以下部分专业化是模棱两可的(我很抱歉更改了各个位的名称,但至少对我而言,使您的代码不臃肿并不是一件容易的事):

#include <utility>

template<typename T,typename = void>
struct A {};

template<typename T,typename U>
struct A<std::pair<T,U>> {};

template<typename U>
struct A<std::pair<int,U>,std::enable_if_t<std::is_same_v<int,U>>> {};

int main() {
  A<std::pair<int,int>> x;
}

看起来很像第二个部分专业化比第一个更专业化,但实际上并非如此。

让我们转到部分排序部分 on cppreference 并阅读所有内容:

非正式地“A 比 B 更专业”意味着“A 接受 B 接受的类型的子集”。

正式地,为了在部分特化之间建立比关系更特化的关系,每个部分首先被转换为一个虚构的函数模板,如下所示:

  • 第一个函数模板与第一个偏特化具有相同的模板参数,并且只有一个函数参数,其类型是一个类模板特化,具有来自第一个偏特化的所有模板参数
  • [同上,但s/first/second/g]。

然后函数模板按照 function template overloading 进行排序。

接下来是一个有趣的例子。

在简化代码的情况下,这意味着与第一个特化对应的虚构函数模板具有签名

template<typename T,typename U>
void f(A<std::pair<T,U>>);

而对应于第二个专业化的那个有签名

template<typename U>
void f(A<std::pair<int,U>>>) {}

这是函数模板的两个不同的重载。因此,通过上面第二个链接中描述的规则,问题已转移到首选哪一个。

老实说,此时我有点迷茫,所以我问了 a question,答案是即使第二个重载将 std::pair 的第一个模板参数固定为 {{1} },第一个重载将 int 的第二个模板参数固定为 A,因此它们中没有一个比另一个更专业。而 void/std::enable_if 不会改变这种情况,因为它被用作类型 (std::enable_if_t,因为我们没有将第二个模板参数传递给 void/{ {1}}) 的函数参数,而不是模板类型参数。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


依赖报错 idea导入项目后依赖报错,解决方案:https://blog.csdn.net/weixin_42420249/article/details/81191861 依赖版本报错:更换其他版本 无法下载依赖可参考:https://blog.csdn.net/weixin_42628809/a
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下 2021-12-03 13:33:33.927 ERROR 7228 [ main] o.s.b.d.LoggingFailureAnalysisReporter : *************************** APPL
错误1:gradle项目控制台输出为乱码 # 解决方案:https://blog.csdn.net/weixin_43501566/article/details/112482302 # 在gradle-wrapper.properties 添加以下内容 org.gradle.jvmargs=-Df
错误还原:在查询的过程中,传入的workType为0时,该条件不起作用 &lt;select id=&quot;xxx&quot;&gt; SELECT di.id, di.name, di.work_type, di.updated... &lt;where&gt; &lt;if test=&qu
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct redisServer’没有名为‘server_cpulist’的成员 redisSetCpuAffinity(server.server_cpulist); ^ server.c: 在函数‘hasActiveC
解决方案1 1、改项目中.idea/workspace.xml配置文件,增加dynamic.classpath参数 2、搜索PropertiesComponent,添加如下 &lt;property name=&quot;dynamic.classpath&quot; value=&quot;tru
删除根组件app.vue中的默认代码后报错:Module Error (from ./node_modules/eslint-loader/index.js): 解决方案:关闭ESlint代码检测,在项目根目录创建vue.config.js,在文件中添加 module.exports = { lin
查看spark默认的python版本 [root@master day27]# pyspark /home/software/spark-2.3.4-bin-hadoop2.7/conf/spark-env.sh: line 2: /usr/local/hadoop/bin/hadoop: No s
使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams[&#39;font.sans-serif&#39;] = [&#39;SimHei&#39;] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -&gt; systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping(&quot;/hires&quot;) public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate&lt;String
使用vite构建项目报错 C:\Users\ychen\work&gt;npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-