C++ - 返回不同的变量类型

标签 c++ templates variables types return

我不知道这是否可行,但也许还有其他解决方案可以满足我的需求。我正在尝试从设置文件中获取设置。它们可以是字符串(如名称)、整数或 bool 值。当然,它们作为文本存储在文件中,但我将创建一个用于打开和返回设置的类,但不是作为字符串,而是作为它们中的每一个的实际内容。

class Settings {
    public:
        Settings(string FileName);
        template <class T> T Setting(string SettingName);
}

例如,构造函数将加载文件、解析设置并将它们存储为 map 。 现在,当我调用 Setting 成员函数时,我希望它确定所请求设置的值是什么类型(如果它是数字,则为整数,如果是“true”或“false”,则为 bool 值,如果是字母数字字符串)并返回该类型的值。一个例子

Settings UserPreferences("Preferences.cfg");
bool AutoLogin = UserPreferences.Setting("autologin");  // return bool
string UserName = UserPreferences.Setting("username"); // return string or char*

我查看了模板,但看起来我必须指定在创建 Settings 对象时我期望的变量,但这不是重点。我很高兴像这样声明要返回的变量类型:

bool AutoLogin = UserPreferences.Setting<bool>("autologin");
string UserName = UserPreferences.Setting<string>("username");

但我不知道这是否可能。你怎么看?

最佳答案

这绝对是可能的,尽管您必须保证它可以转换为给定的类型。这在 XNA 的 ContentLoader(尽管是一个非常不同的系统)中经常看到。您可以使用这种方法来简化和抽象事物的存储和检索方式。考虑:

class Loader
{
private:
    vector<void*> _items;
public:
    template <typename Type>
    Type GetItem( int index ) { return (Type)(_items[ index ]); }
};

这个想法是,只要您可以可靠地将内部数据转换为请求的类型(比示例更可靠),这就是完全合法的操作。如何确保成功完全是另一个问题,但您绝对可以拥有返回类型为其模板类型的方法。考虑以下示例(我使用这是资源加载器的大学项目):

标题.h

class BasicResource
{
public:
    static const int ResourceID;
    const int ID;
    BasicResource( )
        : ID( ResourceID )
    {
    }
};

class Loader
{
private:
    vector<BasicResource*> _items;
public:
    template <typename Type>
    Type GetItem( int index );
};

#include "inline.inl"

内联.inl

template <typename Type>
Type Loader::GetItem( int index )
{
    auto item = _items[ index ];
    if( item != nullptr && item->ID == Type::ResourceID )
    {
        return (Type)_item;
    }
    else
    {
        // Handle the fail case somehow
    }
}

内联文件允许您像往常一样分离逻辑,但将其包含在允许导出模板方法的 header 中。

关于C++ - 返回不同的变量类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18960852/

相关文章:

c++ - Eigen : block 转置?

c++ - 通过 C++ 中的模板参数传递类构造函数

c++ - 函数模板和派生类

c# - 如何检测var是否为字符串

C++ 抽象类运算符重载和接口(interface)强制问题

c++ - 纯 Win32 C++ 中的自定义菜单边框(无 WTL、MFC 等)

c++ - C++ 中的从属名称与非从属名称

c++ - 将引用显式传递到不期望引用的函数模板中会导致问题吗?

javascript - 在函数外更改变量值

php - 错误 “Undefined variable”