Defining a condition in a class

I am trying to do something like:

#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>(){};
};

Is it possible to somehow make such a condition? No, I cannot inherit from this class and I need doSth () ONLY if A<B>, doSth () should not exist if A<C>.

+4
source share
2 answers

You can use std::enable_ifto conditionally make doSthavailable without the need for specialization of the entire class:

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>(){};
};

You need it template <typename U = T>because it std::enable_if_trelies on SFINAE. See std :: enable_if for conditional compilation of a member function for more information.

+5
source

. .

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(){};
};

, .

+2

Source: https://habr.com/ru/post/1689684/


All Articles