如何在模板类中返回成员变量的副本
How do I return a copy of a member variable in a template class?
模板newbie在这里。我正在使用以下测试课程:
template<typename T>
class Container
{
public:
Container(T t) : m_t(t) {}
T clone()
{
return m_t;
}
private:
T m_t;
};
clone()
方法返回成员变量的副本。显然,如果T是指针,例如:
Container<SomeClass*> container(new SomeClass());
clone()
方法只会返回指针而不是完整的克隆。我知道if constexpr
的美感,但不幸的是,我被C 14编译器所困。我想保持我的课程通用,以便它也可以与指针一起使用。我应该创建两种不同的方法吗?Sfinae可以在这里有任何帮助吗?
要专门研究整个课程,正如其他答案所暗示的那样,您可能需要复制很多代码(不是一件好事(。
相反,我建议良好的ol' tag dispatch :
template<typename T>
class Container
{
T clone_low(std::false_type)
{
return m_t;
}
T clone_low(std::true_type)
{
return new std::remove_pointer_t<T>(m_t);
}
public:
Container(T t) : m_t(t) {}
T clone()
{
return clone_low(std::is_pointer<T>{});
}
private:
T m_t;
};
您可以使用类的部分专业化。例如
#include <iostream>
template<typename T>
class Container
{
public:
Container(T t) : m_t(t) {}
T clone()
{
return m_t;
}
private:
T m_t;
};
template<typename T>
class Container<T*>
{
public:
Container(T* t) : m_t(new T(*t)) {}
T* clone()
{
return new T(*m_t);
}
~Container() { delete m_t; }
private:
T* m_t;
};
int main()
{
std::cout << Container<int>(10).clone() << 'n';
int x = 20;
Container<int*> c(&x);
int* p = c.clone();
std::cout << *p << 'n';
delete p;
return 0;
}
相关文章:
- 从私有成员变量的成员方法返回unique_ptr
- 为什么我不能在返回 const 的布尔函数中为类成员变量赋值?C++
- 为什么结构化绑定不使用"auto&"返回对结构成员的引用,而是返回成员本身
- 如何在C++中允许成员函数的自定义返回类型进行类型擦除?
- 在模板化成员函数的返回类型中使用 std::enable_if 时的编译器差异
- 为什么在分配给成员变量之前获取unique_ptr的返回是一个问题?
- C++:如何返回指向非静态成员函数的指针?
- 为什么我可以改变常量对象中的成员变量,这是返回常量对象函数的结果?
- 类方法返回指向具有模板的类成员的指针
- 创建 std::函数,它返回具有函数成员值的变量.分段错误
- 将成员函数的返回类型引用到C++中的自定义类
- 在C++如何从数组中提取成员并返回成员类型的数组?
- C++:私有类指针成员返回未定义的值
- 从类成员返回智能指针的正确方法?
- 在基类指针向量中,如何访问派生的类成员返回错误
- const成员返回为非const
- 通过向成员返回非常量引用来破坏封装
- C++:通过引用将 std::vector<> 成员返回到临时对象
- 从c++中类的函数成员返回一个数组
- 查询的类成员返回错误的值