Farkor123
Farkor123

Reputation: 39

Condition in class definition

I'm 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 even possible to do a condition like this, somehow? No, I can't inherit from this class, and need doSth() ONLY if A<B>, the doSth() should not exist if A<C>.

Upvotes: 4

Views: 414

Answers (2)

songyuanyao
songyuanyao

Reputation: 172924

You can do it with a full specialization. e.g.

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

You can also consider about making a common base class to avoid code duplication.

Upvotes: 2

Vittorio Romeo
Vittorio Romeo

Reputation: 93274

You can use std::enable_if to conditionally make doSth available without having to specialize 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 template <typename U = T> because std::enable_if_t relies on SFINAE. See std::enable_if to conditionally compile a member function for more information.

Upvotes: 5

Related Questions