if-else取决于T是否为完整类型 [英] if-else depends on whether T is a complete type
问题描述
如何检查特定类型.cpp
中特定类型是否为完整类型?
How to check whether a certain type is a complete type in a certain .cpp
?
template<class T>class Test{
//some fields
void(*functor)(T*) =[](T*){};
//^ will be written by some .cpp that can access T as complete-type
T* t=nullptr;
void fComplete(){
delete t; //faster
/** ^ some code that use complete type*/
}
void fForward(){
functor(t); //slower
/** ^ some code that forward declaration is enough*/
}
void f(){
/*if(T is complete type){
fComplete();
}else fForward();*/
}
};
当我想过早地优化自定义智能指针中的删除功能时,它将很有用.
It will be useful when I want to prematurely optimize a delete function in my custom smart pointer.
任何人都可以确认这是不可能的吗?
我不是要解决方法(但我不介意)-这个问题只是我的好奇心.
Can anyone confirm that it is impossible?
I am not asking for a workaround (but I don't mind) - this question is just my curiosity.
推荐答案
有效
#include <iostream>
#include <type_traits>
using namespace std;
class Incomplete;
class Complete {};
template <typename IncompleteType, typename = std::enable_if_t<true>>
struct DetermineComplete {
static constexpr const bool value = false;
};
template <typename IncompleteType>
struct DetermineComplete<
IncompleteType,
std::enable_if_t<sizeof(IncompleteType) == sizeof(IncompleteType)>> {
static constexpr const bool value = true;
};
int main() {
cout << DetermineComplete<Complete>::value << endl;
cout << DetermineComplete<Incomplete>::value << endl;
return 0;
}
注意:我喜欢使用std::enable_if_t
来达到与void_t
相同的效果,直到可用为止,而不是自己到处编写它的实现.
Note I like to use std::enable_if_t
for the same effect as void_t
until that is available instead of writing its implementation myself everywhere.
注意也请查看有关ODR的其他答案.它们提出了您在使用此功能之前应考虑的有效观点.
Note Do take a look at the other answer as well about ODR. They bring up a valid point that you should consider before using this.
这篇关于if-else取决于T是否为完整类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!