0

ネストされた部分的なテンプレート特殊化の構文を理解するのに問題があります。どう考えても正しい言い方だと思います。私が欲しいのはas()、キャストされた値を返す関数です。ほとんどの場合static_castは問題なく動作するので、それを行う汎用バージョンがありますが、場合によっては具体的にしたいことがあります。私が抱えている問題は、共通のtypename.

template<typename ClassType>
class Generic
{
public:
    // Constructors/etc excluded

    template<typename CastType>
    CastType as() const;

private:
    ClassType m_value;
};

// Templated version:
template<typename ClassType> template<typename CastType> inline
CastType Generic<ClassType>::as<CastType>() const
{
    return static_cast<CastType>(m_value);
}

それがセットアップです。実際、それが最善の方法であるかどうかは100%確信が持てませんが、GCCでコンパイルされ、動作するようです.. とにかく。Eigen::Matrix<T,4,1>ここで、部分的にテンプレート化された別のテンプレート化された型 (この場合は-- しかし、おそらくまたは別の型も使用される可能性があります。つまり、 a から aへのstd::vectorキャスト)に特化したいと考えています。std::vector<T>std::list<T>

template<> template<typename CastType> inline
CastType Generic<Eigen::Matrix<CastType,4,1> >::as<CastType>() const
{
    return m_value[0];
}

これは意味がありますか?異なるサイズの Eigen::Matrix を取り、それらを特別に処理するわずかに異なるバージョンはどうですか?

template<> template<typename CastType> inline
Eigen::Matrix<CastType,3,1> Generic<Eigen::Matrix<CastType,4,1> >::as<Eigen::Matrix<CastType,3,1>() const
{
    return Eigen::Matrix<CastType,3,1>( m_value[0], m_value[1], m_value[2] );
}

上記の 2 つのコード ビットが機能せず、構文がおそらくひどいものであることはわかっています。これを解決しようとしています。これが重複している場合はご容赦ください。私はいくつかの同様の質問を見ましたが、どれもこれに関するものではないようでした.

4

1 に答える 1

0

関数は部分的に特殊化できないため、代わりに functionoid-thingy を部分的に特殊化し、関数が単に特殊化されたクラスを使用するようにします。

//generic version
template<typename ClassType, typename CastType> class As { 
public: CastType operator()(const ClassType& b)
    {return static_cast<CastType>(b);}
};
//specialization
template<> class As<int, char* > { 
public: char* operator()(const int& b)
    {throw b;} //so we know it worked
};

//generic class 
template<typename ClassType>
class Generic
{
public:
    Generic() {m_value=0;} //codepad made me put this in
    // Constructors/etc excluded

    template<typename CastType>
    CastType as() const; //as function

private:
    ClassType m_value;
};

// as function simply grabs the right "As" class and uses that
template<typename ClassType> template<typename CastType> inline
CastType Generic<ClassType>::as() const
{
    As<ClassType, CastType> impl;
    return impl(m_value);
}

//main, confirming that it compiles and runs (though I didn't check b...)
int main() {
    Generic<int> gint;
    float b = gint.as<float>();
    char* crash = gint.as<char*>();
}

コード: http://codepad.org/oVgCxTMI 結果:

タイプ int のキャッチされない例外が
中止されました。

于 2011-09-01T20:00:52.487 に答える