模板化赋值运算符模板实例化失败
Templated assignment operator failed template instantiation
我正在尝试构建一个模板化基类,允许分配给其任何模板类型,如下所示:
#include <type_traits>
#include <utility>
template<typename T1, typename... Types>
class Base
{
public:
//assignment to base or derived class
template<typename T, typename std::enable_if<std::is_base_of<Base<T1, Types...>, T>::value>::type = 0>
Base& operator=(T&& other)
{
if (this != &other)
a = other.a;
return *this;
}
//assignment to other type contained in <T1, Types...>
template<typename T, typename std::enable_if<!std::is_base_of<Base<T1, Types...>, T>::value>::type = 0>
Base& operator=(T&& other)
{
// do some stuff
return *this;
}
private:
int a;
};
如您所见,我正在尝试使用std::enable_if
来区分对Base
的赋值(移动或复制)和通过包装std::is_base_of
来区分对类型的赋值。我的印象是T&&
应该绑定到const Base&
、Base&&
、Base&
以及const T&
T&&
等。
当我尝试通过简单地将参数转发到基基来创建支持赋值的派生类时,就会出现问题:
class Derived : public Base<int, double>
{
public:
// similar pattern here, but call base class' operators
// for both copy/move assignment
// as well as assignment to int or double
template<typename T>
Derived& operator=(T&& other)
{
Base<int, double>::operator=(std::forward<T>(other));
return *this;
}
};
一旦我尝试执行我认为应该是有效赋值的操作,编译器就会告诉我它无法执行模板推导/替换。
int main() {
Derived foo;
int a = 4;
foo = a;
return 0;
}
我在这里做错了什么?请放轻松。
现场示例
两个问题:
-
对于左值,转发引用(以及模板类型参数
T
本身)将成为左值引用。在检查类型T
是否是其他类型的子类之前,您应该衰减它。 -
你以错误的方式使用
std::enable_if
;如果你想使用::type = 0
语法,那么它需要一些其他类型,而不是默认的void
。
话虽如此,您的std::enable_if
语法应如下所示:
typename std::enable_if<std::is_base_of<Base<T1, Types...>
, typename std::decay<T>::type // decay of T
>::value
, int>::type = 0 // int as a second template argument
完整示例:
template<typename T, typename std::enable_if<std::is_base_of<Base<T1, Types...>, typename std::decay<T>::type>::value, int>::type = 0>
Base& operator=(T&& other)
{
if (this != &other)
a = other.a;
return *this;
}
//assignment to other type contained in <T1, Types...>
template<typename T, typename std::enable_if<!std::is_base_of<Base<T1, Types...>, typename std::decay<T>::type>::value, int>::type = 0>
Base& operator=(T&& other)
{
// do some stuff
return *this;
}
相关文章:
- 从C++实例化QML
- 使用用户定义的类型 UDT 实例化 std::atomic<>。如果 UDT 具有虚函数,则 l 墨水将失败。为什么?
- 模板实例化失败:编译器选择不正确的重载函数
- 显式实例化失败的原因是什么
- 使编译在模板类的特定实例化时失败
- 类模板的成员函数有条件无效(隐式实例化有效;显式实例化失败)
- 如果实例化,如何使模板化变量专用化在编译时失败
- 在这个失败的C++类实例化中,我忽略了什么明显的事情
- 双模板化函数实例化失败
- 函数模板实例化失败
- 模板实例化与 constexpr 函数失败
- 模板化赋值运算符模板实例化失败
- std::conditional 的可变模板化使用,其中一种类型是实例化失败
- 为什么局部变量的实例化失败,而静态变量没有
- c++ dynamic_cast对装饰器实例化失败
- 由于抽象模板arg的实例化,Boost::lambda表达式编译失败.任何解释和/或解决方法
- 构建libsigc++失败(std::basic_ostream显式实例化)
- 当模板化函数实例化失败时,回退到备用函数
- QtSerialPort在错误的线程中实例化,导致信号/插槽失败
- 可以实例化 C++ 类模板,但具有相同模板参数的函数模板实例化失败