班级定义中的条件

Condition in class definition

本文关键字:条件 定义      更新时间:2023-10-16

我正在尝试做类似的事情:

#pragma once
#include <memory>
#include <type_traits>
#include <vector>
class B{}
template <class T>
class A
{
    private:
        std::vector<std::shared_ptr<T>> ptrVector;
    public:
        A<T>();
        void pushBack(std::shared_ptr<T> t);
        if(std::is_same<T, B>::value)
        {
            void doSth();
        }
        ~A<T>(){};
};

甚至有可能做这样的条件吗?不,我不能从此类中继承,并且仅在A<B>时需要Dosth(),如果A<C>

您可以使用std::enable_if有条件地使doSth可用,而无需专业化整个班级:

template <class T>
class A
{
    private:
        std::vector<std::shared_ptr<T>> ptrVector;
    public:
        A<T>();
        void pushBack(std::shared_ptr<T> t);    
        template <typename U = T>
        auto doSth() -> std::enable_if_t<std::is_same<U, B>::value>;     
        ~A<T>(){};
};

您需要template <typename U = T>,因为std::enable_if_t依赖于Sfinae。请参阅std :: enable_if以有条件地编译成员函数以获取更多信息。

您可以通过完整的专业化来完成。例如

class B {};
template <class T>
class A
{
    private:
        std::vector<std::shared_ptr<T>> ptrVector;
    public:
        A();
        void pushBack(std::shared_ptr<T> t);
        ~A(){};
};
template <>
class A<B>
{
    private:
        std::vector<std::shared_ptr<B>> ptrVector;
    public:
        A();
        void pushBack(std::shared_ptr<B> t);
        void doSth();
        ~A(){};
};

您还可以考虑将公共基类避免复制代码。