Igo*_*gor 3 c++ templates template-specialization c++11 c++14
我想用自定义赋值运算符编写聚合模板结构,如下所示:
template <typename T>
struct Foo {
Foo() = default;
Foo(const Foo&) = default;
Foo& operator=(const Foo& f) { ... }
...
};
Run Code Online (Sandbox Code Playgroud)
现在,如果T是我想要的const限定类型:
Foo& operator=(const Foo& f) = delete;
Run Code Online (Sandbox Code Playgroud)
我能想到的唯一方法是专门化Foostruct:
template<T> struct Foo<const T> {
Foo& operator=(const Foo& f) = delete;
... a lot of code ...
}
Run Code Online (Sandbox Code Playgroud)
但是要专门化这个结构我必须复制粘贴所有剩余的代码(聚合意味着没有继承 - 至少在C++ 17之前,并且不可能将公共代码移动到基类).
有没有更好的方法呢?
我提出了一种自我继承:继承自泛型版本的const特化
template <typename T>
struct Foo
{
Foo() = default;
Foo(Foo const &) = default;
Foo& operator= (Foo const & f) { return *this; }
};
template <typename T>
struct Foo<T const> : public Foo<T>
{
Foo& operator= (Foo const & f) = delete;
};
Run Code Online (Sandbox Code Playgroud)
这样你的const特化继承了泛型版本,因此不需要复制和过去所有公共代码,除了operator=()删除它.
以下是一个完整的例子
template <typename T>
struct Foo
{
Foo() = default;
Foo(Foo const &) = default;
Foo& operator= (Foo const & f) { return *this; }
};
template <typename T>
struct Foo<T const> : public Foo<T>
{
Foo& operator=(Foo const & f) = delete;
};
int main ()
{
Foo<int> fi;
Foo<int const> fic;
fi = fi; // compile
// fic = fic; // compilation error
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
227 次 |
| 最近记录: |