班级定义中的条件
Condition in class definition
我正在尝试做类似的事情:
#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(){};
};
您还可以考虑将公共基类避免复制代码。
相关文章:
- 如何摆脱为条件编译定义预处理器宏的需要?
- 如何在 LIBSVM 中定义具有不同条件的交叉验证?
- 具有迭代器和自定义步长的循环结束条件
- 如何使用 SFINAE 在方法调用中有条件地定义变量?
- C++成员函数的条件模板类定义
- 双循环变量的相等条件:未指定还是未定义
- 如何在C++中定义扩展到条件语句的宏?
- boost::asio::async_read_until 具有自定义匹配条件运算符重载混淆
- 条件C++类成员定义
- 模板定义中的条件
- 智能指针自定义删除器中的处理条件
- c if语句:第一个条件取代第二个ub或定义良好
- 在C++中定义带有条件的宏
- 在"if"条件中定义 fstream
- 根据成员变量的类型是否存在,有条件地定义该变量
- 具有自定义返回类型和"false"返回条件的函数?
- QMAKE附加以定义而不尊重条件
- 有条件地定义了C 中的参考变量
- 班级定义中的条件
- X宏中元素的条件定义