簡體   English   中英

在C ++中,調用模板函數以從模板函數中獲取指針的值

[英]Call template function for the value of a pointer out of a template function, in C++

我正在嘗試為在調用函數中作為模板參數給出的指針調用模板函數。 我的代碼是:

template <>
struct serialize_helper<std::string> {
     // not important code...
    }

};

template <class T>
inline void serializer(const T& obj, StreamType::iterator& res) {

    if(std::is_pointer<T>::value)
    {
        //THIS doesn' work
        serialize_helper<*T>::apply(*obj,res);
    }
    else
        serialize_helper<T>::apply(obj,res);

}

如果我打電話給:

std::string test("test");
serializer(test, res);

一切正常。 但我也希望能夠使用obj指針來調用序列化程序:

std::string test* = new std::string("test");
serializer(test, res);

在調用序列化函數之前,請先取消對指針的引用,請不要提出該建議。 在串行器功能內部,這是可能的。

簡短說明:我想使用std::string*調用serializer ,並且如果我使用它指向的std::string調用,則具有相同的功能。

模板函數的整個主體都需要為其實例化的類型進行編譯,而不管是否將采用分支。 要解決此問題,可以為何時T是指針,何時不是T定義單獨的函數。

使用SFINAE:

template <class T, std::enable_if_t<std::is_pointer<T>::value>* = nullptr>
inline void serializer(const T& obj, StreamType::iterator& res) {
    serialize_helper<std::remove_pointer_t<T>>::apply(*obj,res);
}

template <class T, std::enable_if_t<!std::is_pointer<T>::value>* = nullptr>
inline void serializer(const T& obj, StreamType::iterator& res) {
    serialize_helper<T>::apply(obj,res);
}

使用標簽發送:

template <class T>
inline void serializer(const T& obj, StreamType::iterator& res, std::true_type) {
    serialize_helper<std::remove_pointer_t<T>>::apply(*obj,res);
}

template <class T>
inline void serializer(const T& obj, StreamType::iterator& res, std::false_type) {
    serialize_helper<T>::apply(obj,res);
}

template <class T>
inline void serializer(const T& obj, StreamType::iterator& res) {
    serializer(obj, res, std::is_pointer<T>());
}

我會喜歡這樣的東西

template <class T>
inline void serializer(const T& obj, StreamType::iterator& res) {
    serialize_helper<T>::apply(obj,res);
}

template<class T>
inline void serializer(T* obj, StreamType::iterator& res) {
    serialize_helper<T>::apply(*obj,res);
}

您可以使用std::remove_pointerstd::enable_if

template <class T, typename std::enable_if<std::is_pointer<T>::value>::type* = nullptr>
inline void serializer(const T& obj) {
    serialize_helper<typename std::remove_pointer<T>::type>::apply(*obj);
}

template <class T, typename std::enable_if<!std::is_pointer<T>::value>::type* = nullptr>
inline void serializer(const T& obj) {
    serialize_helper<T>::apply(obj);
}

請注意,為簡單起見,我刪除了StreamType

現場演示

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM