C++ 存储初始化类时使用的模板

C++ 存储初始化类时使用的模板,c++,templates,C++,Templates,我正在尝试找出如何存储我的模板,我将编写一个示例: class cDebugInfo { private: DWORD * address; string name; template Type; public: Type GetFormattedValue() { return *(Type*)address; } cDebugInfo(){} template <class T> cDebu

我正在尝试找出如何存储我的模板,我将编写一个示例:

class cDebugInfo
{
private:
    DWORD * address;
    string name;
    template Type;

public:
    Type GetFormattedValue()
    {
        return *(Type*)address;
    }
    cDebugInfo(){}
    template <class T>
    cDebugInfo(DWORD Address, string Name){
        address = Address;
        name = Name;
        Type = T;
    }
};
这应该以INT read形式返回给定地址中的值,因为我添加项时传递的模板是INT。当然,下面应该以字符串形式返回存储在指针指向的地址中的值:

GetItemByName("Test2")->GetFormattedValue();
我需要它“记住”传递给类的模板。 注意:当我将GetItemByName与模板一起使用时,其他一切都可以正常工作,但问题是,当我获得它们时,我不知道它是什么模板,只有当我添加它们时。
谢谢。

你所要求的是不可能的,因为C++中的每个表达式在编译时都必须有已知的类型。考虑这一点:

auto value = GetItemByName("BestItem")->GetFormattedValue();
GetItemByName(…)
给了我一个
cDebugInfo*
,但是
GetFormattedValue()
给了我什么?对于每个
cDebugInfo*
,该类型必须是相同的,以便上述表达式可以有效,因此该类型不能保留到运行时。因此,总的解决方案是不可能的

但是,您可以根据需要添加特定的解决方案。假设我们只想打印格式化的值。我们可以做到:

class cDebugInfo {
    std::function<void()> printer; // type-erased functor
    ...
public:
    template <class T>
    cDebugInfo(DWORD Address, string Name){
        address = Address;
        name = Name;
        printer = [this]{
            std::cout << "Value as " << typeid(T).name() << ": "
                      << *reinterpret_cast<T*>(address) << '\n';
        };
    }
};
以便:

GetItemByValue("BestItem")->printValue();

将根据构造该值时使用的类型正确打印该值。

如何
GetItemByName(“Test”)->GetFormattedValue()?有几种方法存储类型信息;困难的部分是如何提取它。在
GetFormattedValue
的调用站点,您需要静态地知道返回类型是什么(除非您想要返回一个有区别的联合,比如Boost.any)。奇怪的是,格式化的值通常意味着一个字符串-你确定你不只是想控制格式化并取回一个字符串吗?@ixSci是的,如果我也使用一个模板,如上所述,它就可以工作。但是我需要检索这个值,而不知道它是int还是布尔或者什么。你可以在C++中搜索“类型擦除”,看看100%。C++中的动态是不可能的。你想要的东西在C++中是不可实现的。你最好的选择是像前面所说的那样的
boost.any
boost.typeerasure
。没有什么更好的事情可以做,因为C++不支持这样的动态性。哇,谢谢,我的目标是把它存储在一个字符串中并在我的日志中打印,这正是我想要的:DUI可以比这更容易地存储文本。
auto value = GetItemByName("BestItem")->GetFormattedValue();
class cDebugInfo {
    std::function<void()> printer; // type-erased functor
    ...
public:
    template <class T>
    cDebugInfo(DWORD Address, string Name){
        address = Address;
        name = Name;
        printer = [this]{
            std::cout << "Value as " << typeid(T).name() << ": "
                      << *reinterpret_cast<T*>(address) << '\n';
        };
    }
};
void printValue() { printer(); }
GetItemByValue("BestItem")->printValue();