4

C++ では、さまざまな型変換が暗黙的に行われます。たとえば、タイプのオブジェクトをint割り当てることができますconst int(以下のコードの main 関数の最初の行で行われているように)。

ここで、型を追加できる構造があるという意味で、実行時に変換可能かどうかを確認したいと思います。後で、構造に格納されている型の 1 つが特定の型に変換可能かどうかを確認したいと思います。

これが私がこれまでに思いついたものです:

#include <iostream>
#include <vector>

struct bar { virtual void dummy() {} };
template<typename T> struct foo : public bar { virtual void dummy() {} };

int main() {

    int i1 = 1;
    const int i2 = i1;

    std::vector<bar*> bars;
    bar* t1 = new foo<int>; bars.push_back(t1);
    bar* t2 = new foo<int const>; bars.push_back(t2);

    foo<int const>* t3 = dynamic_cast<foo<int const>*>(bars[0]);
    std::cout << t3 << std::endl;

    foo<int const>* t4 = dynamic_cast<foo<int const>*>(bars[1]);
    std::cout << t4 << std::endl;

    delete t1;
    delete t2;

    return 0;
}

foo型を構造体に格納するために、から派生したテンプレート化された構造体を作成しましたbar。次に、さまざまな型intand (正確には型andint constのオブジェクトへのポインター) を s のベクトルに格納できます。次に、特定の型 (ここでは) について、この型の に動的にキャストできるかどうか、このベクターの各要素をチェックします。foo<int>foo<int const>bar*int constfoo

このコードを実行すると、null 以外のポインターにt3なります。しかし、null以外のポインターも必要でした。nullptrt4t3

私がやりたいことがほぼ明確になったことを願っています。

実行時にこの種の可換性をチェックする方法について何かアイデアはありますか (c++11 の機能を含むソリューションはまったく問題ありません)。

4

2 に答える 2

-1

Use std::is_convertible<From*, To*>::value

#include<type_traits>
int main(){
    using namespace std;
    cout << std::is_convertible<int const, int>::value << endl; // print true
    cout << std::is_convertible<int const*, int*>::value << endl; // print false
    cout << std::is_convertible<int const, int>::value << endl; // print true
    cout << std::is_convertible<std::string, int>::value << endl; // print false
    cout << std::is_convertible<std::string*, int*>::value << endl; // print false
}

Note that you have to use the pointer type to obtain the excepted behavior with respect to constness for example.

(I guess in C++98 you can do the same with boost::is_convertible.)

于 2013-06-28T21:19:39.007 に答える