Ale*_*tov 5 c++ templates specialization compile-time-constant type-traits
假设我们有以下模板类
template<typename T> class Wrap { /* ... */ };
Run Code Online (Sandbox Code Playgroud)
我们无法改变 Wrap.这很重要.
让我们有来自的类Wrap<T>.例如,
class NewInt : public Wrap<int> { /* ... */ };
class MyClass : public Wrap<myclass> { /* ... */ };
class Foo : public Wrap<Bar> { /* ... */ };
Run Code Online (Sandbox Code Playgroud)
我们也不能改变这些类.以上所有课程均为第三方.他们不是我的.
我需要以下编译时间type_traits:
template<class T>
struct is_derived_from_Wrap {
static const bool value = /* */;
};
Run Code Online (Sandbox Code Playgroud)
我需要什么?
assert(is_derived_from_Wrap<Int>::value == true); // Indeed I need static assert
assert(is_derived_from_Wrap<MyClass>::value == true);
assert(is_derived_from_Wrap<char>::value == false);
struct X {};
assert(is_derived_from_Wrap<X>::value == false);
Run Code Online (Sandbox Code Playgroud)
你可以使用SFINAE做到这一点,但如果你不知道发生了什么,它会有点神奇......
template<typename T> class Wrap { };
struct myclass {};
struct X {};
class Int : public Wrap<int> { /* ... */ };
class MyClass : public Wrap<myclass> { /* ... */ };
template< typename X >
struct is_derived_from_Wrap
{
struct true_type { char _[1]; };
struct false_type { char _[2]; };
template< typename U >
static true_type test_sfinae( Wrap<U> * w);
static false_type test_sfinae( ... );
enum { value = sizeof( test_sfinae( (X*)(0) ) )==sizeof(true_type) };
};
#include <iostream>
#define test(X,Y) std::cout<<( #X " == " #Y )<<" : "<<( (X)?"true":"false") <<std::endl;
int main()
{
test(is_derived_from_Wrap <Int>::value, true);
test(is_derived_from_Wrap <MyClass>::value, true);
test(is_derived_from_Wrap <char>::value, false);
test(is_derived_from_Wrap <X>::value, false);
}
Run Code Online (Sandbox Code Playgroud)
这给出了预期的输出
is_derived_from_Wrap <Int>::value == true : true
is_derived_from_Wrap <MyClass>::value == true : true
is_derived_from_Wrap <char>::value == false : false
is_derived_from_Wrap <X>::value == false : false
Run Code Online (Sandbox Code Playgroud)
我的代码有几个问题.如果类型是Wrap,它也将返回true.
assert( is_derived_from_Wrap< Wrap<char> >::value == 1 );
Run Code Online (Sandbox Code Playgroud)
如果需要,可以使用更多SFINAE魔法修复此问题.
如果派生不是公共派生(即私有或受保护),它将返回false
struct Evil : private Wrap<T> { };
assert( is_derived_from_Wrap<Evil>::value == 0 );
Run Code Online (Sandbox Code Playgroud)
我怀疑这不能修复.(但我可能错了).但我怀疑公共继承就足够了.
| 归档时间: |
|
| 查看次数: |
388 次 |
| 最近记录: |