2

この質問は、 「型ではなく変数NAMESをテンプレート化する方法」で見つかった以前の質問の続きです。

次のコードがあるとしましょう。

struct VAR_TYPE{
public:
    bool is_fixed; 
    double value;      // Numerical value
    std::string name;  // Description of variable (to identify it by name)
    int reference_counter;
    /* ect. */
};

struct NODE{
public:
    VAR_TYPE X, Y, Z;
    /* ect. */
};

class MyClass{
public:
    std::vector <NODE_ptr> node;  // shared ptr, using boost::shared_ptr

    // what I have now
    void set_variable_X(int &i, double &P) { node[i]->X.value = P; }
    void set_variable_Y(int &i, double &P) { node[i]->Y.value = P; } 
    void set_variable_Z(int &i, double &P) { node[i]->Z.value = P; }

    // What I want to replace all 3 members with:
    <class T, class N>
    void set_variable( int &i, double &P, /* ??? */ ) { /* ??? */ }
    /* ect. */
};

'???'のある地域で何が起こるかわかりません 書かれた。前述のリンクで使用されている擬似コードを借りて、

main(){
    MyClass S;
    double x1, y1, z1;
    int index; 

    // set x1, y1, z1, index

    S.set_variable( index, x1, &MyClass::node::X ); // in essence, what I want
    S.set_variable( index, y1, &MyClass::node::Y );
    S.set_variable( index, z1, &MyClass::node::Z );
};

私はいくつかのアイデアを試しましたが、エラーが発生します。問題は、ブースト共有ポインターやstd::vectorを使用しているという事実にあると思います。誰もが問題と適切な解決策が何であるかについての考えを持っていますか?私が取り組んできたオプションの1つは、次のとおりです(ただし、上記のint main()で特定した呼び出し規約は使用しません)。

template < class T, class N >
void MyClass::set_reference( int &i, double &P,  
                         T NODE::* MemPtr,
                         N VAR_TYPE::* ValPtr)
{
    *MemPtr[i].*ValPtr.value = P; // doesn't work work
};
4

1 に答える 1

1

以下はあなたが望むように見えることをします:

#include <string>
#include <vector>
struct VAR_TYPE{
public:
    bool is_fixed; 
    double value;      // Numerical value
    std::string name;  // Description of variable (to identify it by name)
    int reference_counter;
    /* ect. */
};

struct NODE{
public:
    VAR_TYPE X, Y, Z;
    /* ect. */
};

class MyClass{
public:
    std::vector <NODE *> node;  // shared ptr, using boost::shared_ptr

    // what I have now
    void set_variable_X(int &i, double &P) { node[i]->X.value = P; }
    void set_variable_Y(int &i, double &P) { node[i]->Y.value = P; } 
    void set_variable_Z(int &i, double &P) { node[i]->Z.value = P; }

    // What I want to replace all 3 members with:
    void set_variable( int &i, double &P, VAR_TYPE NODE::* ptr ) { (node[i]->*ptr).value = P;}
    /* ect. */
};


main(){
    MyClass S;
    double x1, y1, z1;
    int index; 

    // set x1, y1, z1, index

    S.set_variable( index, x1, &NODE::X ); // in essence, what I want
    S.set_variable( index, y1, &NODE::Y );
    S.set_variable( index, z1, &NODE::Z );
}

「変数を名前で呼ぶためのテンプレート」とはどういう意味かわかりませんが。ところで、通過する理由は何もありませんしiP参照することもできません。そうすべきではありません。

于 2012-09-24T17:59:51.847 に答える