如何在模板类中返回成员变量的副本

How do I return a copy of a member variable in a template class?

本文关键字:成员 返回 变量 副本      更新时间:2023-10-16

模板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;
}