我有這個帶有模板功能的代碼。該函式可以接受從 Object 繼承的任何物件,或者使用提供指向 Object 實體的指標的運算子。在函式內部,我需要獲取 Object 指標,但它是模板型別,我無法弄清楚如何指定模板型別。
這是代碼:
class IObject
{
};
template<class T>
class Object: public IObject
{
typedef T value_type;
public:
void test()
{
}
operator Object<T>*()
{
return this;
}
};
template<class T>
class Wrapper
{
typedef T value_type;
public:
T object;
operator T*()
{
return &object;
}
};
template<class T>
class Container
{
public:
void func()
{
data.resize(1);
typename T::value_type& ref = data[0];
//IObject* object = ref; //works
Object<?>* object = ref; // How can I specify the template type here?
object->test();
};
T data;
};
int main()
{
Container<std::vector<Object<float>>> container1;
container1.func();
Container<std::vector<Wrapper<Object<int>>>> container2;
container2.func();
return 0;
}
我嘗試使用 value_type,但由于技術上有 2 種型別的物件可以用作輸入,它不起作用。我還嘗試向函式模板添加額外的引數,但編譯器無法推斷出引數型別。
uj5u.com熱心網友回復:
首先,要么你Wrapper錯了,要么你對它的使用是錯誤的。你實體化Wrapper<Object<int>>,但在你的類中:
Object<T> object;
operator Object<T>*()
它被實體化為
Object<Object<int>> object;
operator Object<Object<int>>*()
您應該實體化Wrapper<int>,這將“包裝” a Object<int>,或者更改您的類以改為:
T object;
operator T*()
但那typedef T value_type是錯誤的。
在任何情況下,您都可以創建一個型別特征來“解包”該型別:
template<class T>
struct UnwrapT {
using type = T;
};
template<class T>
struct UnwrapT<Wrapper<T>> {
using type = Object<T>;
};
template<class T>
using Unwrap = typename UnwrapT<T>::type;
然后您可以在以下位置使用它func:
Unwrap<typename T::value_type>* object = ref;
演示
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/532075.html
標籤:C 模板c 20
上一篇:將字串推回vector<T>
