【问题标题】:Is there any way to derive the object type from a member pointer type in C++有没有办法从 C++ 中的成员指针类型派生对象类型
【发布时间】:2013-02-19 17:17:09
【问题描述】:

是否可以编写一个 C++ 模板owner_of<...> 使得给定以下代码:

struct X { int y; }

owner_of<&X::y>::typeX

【问题讨论】:

  • 是的,您可以部分专门化 owner_of
  • @MarcGlisse:我正在努力构建语法 - 请告诉我如何?

标签: c++ templates c++11 metaprogramming


【解决方案1】:

几乎可以这样做(或者至少到目前为止我找不到更好的解决方案):

#include <string>
#include <type_traits>

using namespace std;

template<typename T>
struct owner_of { };

template<typename T, typename C>
struct owner_of<T (C::*)>
{
    typedef C type;
};

struct X
{
    int x;
};

int main(void)
{
    typedef owner_of<decltype(&X::x)>::type should_be_X;
    static_assert(is_same<should_be_X, X>::value, "Error" );
}

如果您介意使用decltype,也许宏可以做到:

#define OWNER_OF(p) owner_of<decltype( p )>::type

int main(void)
{
    typedef OWNER_OF(&X::x) should_be_X;
    static_assert(is_same<should_be_X, X>::value, "Error" );
}

基于decltype:的替代解决方案

template<typename T, typename C>
auto owner(T (C::*p)) -> typename owner_of<decltype(p)>::type { }

int main(void)
{
    typedef decltype(owner(&X::x)) should_be_X;
    static_assert(is_same<should_be_X, X>::value, "Error" );
}

【讨论】:

  • 不幸的是我把我的例子删减了太多。我真正在寻找的是一种将some_class&lt;X, &amp;X::x&gt; 减少到some_class&lt;&amp;X::x&gt; 的方法
  • @Eric:那我恐怕你做不到。文字没有等效的“类型名”。与“typename”接受任何类类型的方式相同,您需要一个接受任何文字的“literal”,然后您将对其进行专门化。但不幸的是,不存在这样的事情。
  • @Eric:正如安迪所说,还没有人找到办法做到这一点。您能做的最好的事情是some_class&lt;decltype(&amp;X::x), &amp;X::x&gt; 并将其隐藏在宏后面。 :/ 另见this question
  • @AndyProwl:我会相信你的话。这仍然很有帮助,所以我接受了 - 谢谢。
猜你喜欢
  • 2017-03-09
  • 2018-04-26
  • 2010-09-25
  • 2017-07-18
  • 2014-06-16
  • 1970-01-01
  • 2021-07-02
  • 2021-02-20
  • 1970-01-01
相关资源
最近更新 更多