0

当涉及到类型推断管理时, C++11包含大量出色的功能。例如autodecltype -keywords 已被证明是该语言的一个有价值的补充。

当我采用这些简单而有效的特性时,我开始考虑实现某种反射系统。这是我到目前为止所取得的成果:

/// ------------------------------------------------------------
/// @class  Reflection
/// @brief  General-purpose reflection class.
/// @exmpl  Get type id:
///             auto a = Reflection::get_id_type<int>();
///             auto b = Reflection::get_id_type<Object>();
///         Get type via received id:
///             decltype(Reflection::get_type(a)) d;
/// @note   It is forbidden to create an instance of this class.
/// ------------------------------------------------------------
class Reflection{
public:
    /// Static member functions:
    template<typename T>
    static inline long get_id_type(void){
        return reinterpret_cast<long>(&Database<T>::id);
    }
    static auto get_type(long const type_id) -> decltype(/* UNFINISHED! */){ // This is where I'm having problems.
        // This function body is intentionally left empty.
        // All that matters is the return type.
    }
private:
    /// Inner structures:
    template<typename T>
    struct Database{
        static void* id; // Created void pointer here, because only the address of this variable matters.
    };
    /// Constructors & destructors:
    Reflection(void) = delete;
    ~Reflection(void) = delete;
    /// Member functions (overloaded operators):
    Reflection& operator=(Reflection&&) = delete;
    Reflection& operator=(Reflection const&) = delete;
};

代码应该足够容易理解。如果您阅读带有注释的整体代码,您应该知道如何使用这个类。但问题是:

“如何从函数“get_type”返回一个表达式,以便通过decltype -specifier 将此表达式转换为可用类型?

提前致谢。

4

1 回答 1

4

您不能拥有取决于参数的运行时值的返回类型。时期。你试图做的事情是不可行的。

于 2012-09-07T14:49:54.430 回答