問題描述
在回答這個問題后,我試圖找到is_complete
Boost 庫中的模板,我意識到 Boost.TypeTraits 中沒有這樣的模板.為什么Boost庫中沒有這樣的模板?它應該是什么樣子?
After answering this question I was trying to find is_complete
template in Boost library and I realized that there is no such template in Boost.TypeTraits. Why there is no such template in Boost library? How it should look like?
//! Check whether type complete
template<typename T>
struct is_complete
{
static const bool value = ( sizeof(T) > 0 );
};
...
// so I could use it in such a way
BOOST_STATIC_ASSERT( boost::is_complete<T>::value );
上面的代碼是不正確的,因為將 sizeof
應用于不完整的類型是非法的.什么是好的解決方案?在這種情況下是否可以以某種方式應用 SFINAE?
The code above is not correct, because it is illegal to apply sizeof
to an incomplete type. What will be a good solution? Is it possible to apply SFINAE in this case somehow?
好吧,如果不違反ODR 規則,一般無法解決這個問題,但是有一個特定于平臺的解決方案對我有用.
Well, this problem couldn't be solved in general without violating the ODR rule, but there is there a platform specific solution which works for me.
推薦答案
Alexey Malistov 給出的答案稍加修改即可用于 MSVC:
The answer given by Alexey Malistov can be used on MSVC with a minor modification:
namespace
{
template<class T, int discriminator>
struct is_complete {
static T & getT();
static char (& pass(T))[2];
static char pass(...);
static const bool value = sizeof(pass(getT()))==2;
};
}
#define IS_COMPLETE(X) is_complete<X,__COUNTER__>::value
不幸的是,__COUNTER__
預定義宏不是標準的一部分,因此它不適用于每個編譯器.
Unfortunately, the __COUNTER__
predefined macro is not part of the standard, so it would not work on every compiler.
這篇關于如何編寫`is_complete`模板?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!