c++ - 在类中声明具有类型特征的友元函数的问题
问题描述
我正在玩 C++ 中的单例模式,并希望实现一个完成类构建的全局函数。我std::is_base_of
在该函数中使用过,但这使我无法在类中声明该函数。
这是一个简短的示例:
#include <type_traits>
class A {};
template<typename T>
typename std::enable_if_t<std::is_base_of_v<A, T>, T*>
Instance() { return T(); }
template<typename T>
typename std::enable_if_t<!std::is_base_of_v<A, T>, T*>
Instance() { return T(); }
class B : public A {
protected:
B();
friend B* Instance<B>(); // Error
};
上面的代码在实例化第一个函数时使用 gcc 或C2139使用 MSVC会导致“不完整类型的无效使用” 。
那么,除了让构造函数B::B()
公开之外,我还有什么办法可以解决它吗?
解决方案
问题是在定义类期间,类仍然不完整,
和std::is_base_of
所需的完整类型Derived
,否则你有 UB。
如果您有权访问 C++17,您可能会这样做:
template<typename T>
T* Instance() {
if constexpr (std::is_base_of_v<A, T>) {
return nullptr; // Your impl
} else {
return nullptr; // Your impl
}
}
class B : public A {
protected:
B();
friend B* Instance<B>();
};
推荐阅读
- webpack - Webpack 代码拆分:配置对象无效
- php - 在php中将三维数组转换为二维数组
- angularjs - 加载`
- amazon-web-services - SNS SQS - 未收到从 SNS 主题推送到队列的消息
- sql - 使用 SQL 获取 XML 节点中的值
- jquery - 如何在按钮内找到元素的类名?
- django - “parcella_pk”在那里不行,它会导致“ValueError”。我应该使用什么?
- prometheus - Prometheus 查询以获取自午夜以来的指标值或动态偏移量
- unit-testing - 如何从 SOAP UI 工具中的属性传递 SOAP 请求中的输入值?
- flutter - 带有加载微调器和确认的颤振 showDialog