Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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>.

like image 429
Farkor123 Avatar asked Mar 08 '23 12:03

Farkor123


2 Answers

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.

like image 179
Vittorio Romeo Avatar answered Mar 13 '23 07:03

Vittorio Romeo


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.

like image 38
songyuanyao Avatar answered Mar 13 '23 06:03

songyuanyao