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>
.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With