【发布时间】:2014-12-09 14:24:39
【问题描述】:
我正在尝试构建一个模板化基类,它允许分配给它的任何模板类型,如下所示:
#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;
}
我在这里做错了什么?请对我放轻松。
【问题讨论】: