Home > Archives > 2006年01月06日

2006年01月06日

サブクラス判定

ちゃんと探せば STL や Boost に is_convertible と is_base とかがあった.肝を抜き出してみるとこんなもん.

#include <iostream>
using namespace std;
 
template<typename From, typename To>
struct isConvertible {
    static char test(To);
    static long test(...); // variable argument で逃げる
    static From from();
    static const bool value = sizeof(test(from())) == 1;
};
 
class A {};
class B : public A {};
 
int main(int argc, char *argv[])
{
    cout << isConvertible<A, B>::value << endl;
    cout << isConvertible<B, A>::value << endl;
    return 0;
}

test 関数の呼び出しで From から To に変換できる場合は test(To) が選択され,sizeof(test(from())) = 1 となるので value = true となる.そうでなければ test(...) が選択され sizeof(test(from())) != 1 で value = false と.variable arguments 使って型指定をなくせるのに気づかなかった...

もう少し高度なトリックを使うと次の is_base のメイン部分になるらしい.

#include <iostream>
using namespace std;
 
template <typename Super, typename Sub>
struct isSuperclasOf {
    template<typename T>
    static char test(Sub &, T);    
    static long test(Super &, int);
    struct C {
        operator Super &() const;
        operator Sub &();
    };
    static const bool value = sizeof(test(C(), 0)) == 1;
};
 
class A {};
class B : public A {};
 
int main(int argc, char *argv[])
{
    cout << isSuperclasOf<A, B>::value << endl;
    cout << isSuperclasOf<B, A>::value << endl;
    return 0;
}

http://tinyurl.com/502fhttp://tinyurl.com/6jvyq に原理が書いてある.結局はある変換系列が他の変換系列の prefix になっているなら短い型変換が優先で,テンプレート有り関数とテンプレート無し関数では無い関数が優先であることを使っているらしい.Super が Sub の親クラスの場合,test(Super&, int) が呼ばれるには C → Sub → Super の変換列をとり( C → C const → Super 側は無視される),一方で test(Sub&, int) は C → Sub という変換列となる.このとき, C → Sub が C → Sub → Super の prefix になっているので test(Sub&, int) が選択される.よって,sizeof(test(C(), 0)) が 1 になるので value が true になる.Super が Sub の親クラスで無い場合は,test(Super&, int) が呼ばれるには C → C const → Super という変換列となり,これは C → Sub に吸収されないので test(Super&, int) と test(Sub&, int) の可能性がある.しかし,test(Sub&, int) に関してはテンプレートの instantiation があるので test(Super&, int) が選択される.よって,この場合は sizeof(test(C(), 0)) が 1 でないので value が false になる.

よくかんがえるもんだなぁ.

Home > Archives > 2006年01月06日

Search
Feeds

Page Top