【问题标题】:C++11 - Returning an expression to determine a typeC++11 - 返回表达式以确定类型
【发布时间】:2012-09-01 11:20:43
【问题描述】:

C++11类型推断管理 方面包含大量出色的功能。例如 autodecltype - 关键字已被证明是该语言的一个有价值的补充。

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

/// ------------------------------------------------------------
/// @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;
};

代码应该足够容易理解。如果您阅读了 cmets 的整体代码,您应该了解如何使用这个类。但问题是:

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

提前致谢。

【问题讨论】:

  • 这看起来很有趣......出于某种原因,我想起了永动机:-)
  • 即使你能做到这一点,我也不确定它对你的反射系统有什么帮助。对于反射,您需要能够确定类在运行时具有哪些成员。

标签: c++ types c++11 return decltype


【解决方案1】:

你不能有一个依赖于参数的运行时值的返回类型。时期。您尝试做的事情是不可行的。

【讨论】:

  • 感谢您的快速回复!你会推荐我做什么?
  • @user1531111 首先,如果可能的话,我会完全摆脱这种需求。如果真的有必要,你会被传统的解决方案困住:手工制作的类型信息对象,可能在宏的帮助下。 C++11 在这里没有任何帮助。反射基本上相当于将类型信息从编译时传送到运行时(这就是为什么你的方法永远适用于 C++),而 C++ 仍然只有一种机制,即 RTTI。
  • 这可能有点跑题了,但是最好有一个名为“ReflectionDatabase”的基类,派生您希望从中应用反射机制的每个类,并且,当您这样做时,通过 ReflectionDatabase 中的指针管理派生类?
  • 我对常用的技术不是很熟悉,但我知道 Stack Overflow 上还有其他关于它的问题。您可能会发现搜索问题很有趣tagged c++ and reflection
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-11-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-08-06
相关资源
最近更新 更多