无法使用`enable_if`和`is_base_of`将模板函数`operator +`的重载限制为我的类层次结构 [英] Can't restrict overload of template function `operator+` to my class hierarchy using `enable_if` and `is_base_of`

查看:207
本文介绍了无法使用`enable_if`和`is_base_of`将模板函数`operator +`的重载限制为我的类层次结构的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用模板函数为类型层次结构创建operator+.第一次简单的尝试就可以正常工作,直到我尝试在代码的另一部分中连接字符串,并且GCC 8.3尝试使用我的operator+.

I'm creating an operator+ using a template function for a type hierarchy. First simple attempt worked fine until I tried to concatenate a string in another part of the code and GCC 8.3 tried to use my operator+.

尝试使用enable_ifis_base_of将我的版本限制为我的类型,以便SFINAE处理该问题.

Trying to use enable_if and is_base_of to restrict my version to my types so SFINAE handles the issue.

许多尝试中的一种是:

template <  //
    typename T1, //
    typename T2, typename std::enable_if_t<std::is_base_of_v<LogicGateAbs, T2>, T2>       //
>
inline OrGate operator +(T1&& lhs, T2&& rhs) {
    return OrGate { LogicGateAbs::make_concrete(lhs), LogicGateAbs::make_concrete(rhs) };
}

在这里,编译器会正确给出类型:

Here the compiler gives the types correctly:

./src2/test.cpp:90:11: error: no match for ‘operator+’ (operand types are ‘TrueGate’ and ‘TrueGate’)
     (True + True);
      ~~~~~^~~~~~

但是为什么由于LogicGateAbsTrueGate的基数而又为is_base_of返回'false'?

But why does it then return 'false' for is_base_of since LogicGateAbs is the base of TrueGate?

../src2/test.cpp:83:15: note: candidate: ‘template<class T1, class T2, typename std::enable_if<is_base_of_v<LogicGateAbs, T2>, T2>::type <anonymous> > OrGate operator+(T1&&, T2&&)’
 inline OrGate operator +(T1&& lhs, T2&& rhs) {
               ^~~~~~~~
../src2/test.cpp:83:15: note:   template argument deduction/substitution failed:
../src2/test.cpp:81:32: error: no type named ‘type’ in ‘struct std::enable_if<false, TrueGate&>’
     typename T2, typename std::enable_if_t<std::is_base_of_v<LogicGateAbs, T2>, T2>       //
                                ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

在StackOverflow上浏览了此版本的每个版本,而没有一个版本可以正常工作.

Gone through every version of this on StackOverflow without getting a version to work.

基本功能根据需要工作.右值引用是必需的,因为输入通常是临时值.

The base function works as needed. The rvalue reference is necessary for the inputs are often temporary values.

推荐答案

请注意错误消息中的TrueGate&:T2,其推论是因为该参数是一个左值. std:is_base_of需要实际的类类型,所以请使用std::remove_reference_t.

Notice the TrueGate& in the error message: that’s T2, deduced as such because the argument is an lvalue. std:is_base_of requires actual class types, so use std::remove_reference_t.

这篇关于无法使用`enable_if`和`is_base_of`将模板函数`operator +`的重载限制为我的类层次结构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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