Jos*_*ams 5 c++ templates c++17
我有一个模板类,我想根据模板类型来切换其中的内容是否为常量。
伪代码:
template<bool isConst>
Class ConstableClass
{
public:
// if isConst == true make this method const
void DoSomething() "const";
// if isConst == true make the returned smartpointer type const method const
std::unique_ptr<"const" int> operator->() "const";
private:
// if isConst == true add const at the start of the next line
"const" int foo;
}
Run Code Online (Sandbox Code Playgroud)
这种事情可能吗?
不,这是不可能的。虽然有一种方法可以操作成员变量类型和函数返回类型,但无法向方法添加/删除 const 说明符。这意味着您必须为模板参数的 true 和 false 值编写 2 个单独的类定义专业化。