【问题标题】:Metafunction returning element type using decltype使用 decltype 的元函数返回元素类型
【发布时间】:2019-09-18 11:42:56
【问题描述】:

我有以下 MWE:

#include <memory>

template<typename T>
class Foo
{
    public:
        using message_type = T;
};

int main()
{
    std::shared_ptr<Foo<int>> ptr;
    decltype(ptr)::element_type::message_type number = 5;

    return 0;
}

我想有一种速记方法来访问变量的message_type 类型(例如ptr),而不必写出整个decltype(ptr)::element_type::message_type 部分。 IE。沿着message_type(ptr) 的谎言给decltype(ptr)::element_type::message_type 加上一些别名,这将产生相同的结果。

我的第一个想法是

template<typename T>
using message_type = decltype(T)::element_type::message_type;

起初看起来很合乎逻辑,但实际上它混合了类型和变量的概念,因此它甚至无法编译。到目前为止,我唯一可行的解​​决方案是

#define MSG_TYPE(x) decltype(x)::element_type::message_type

但是我想避免使用宏。

当前的 C++ 元编程是否也能做到这一点?如果是这样,正确的语法是什么?

【问题讨论】:

  • 也许template&lt;typename T&gt; using message_type = T::element_type::message_type; 通过decltype() 使用它(我的意思是:message_type&lt;decltype(ptr)&gt; number = 5;)?

标签: c++ template-meta-programming decltype


【解决方案1】:

这行得通:

#include <memory>

template<typename T>
using message_type = typename T::element_type::message_type;

template<typename T>
class Foo
{
    public:
        using message_type = T;
};

int main()
{
    std::shared_ptr<Foo<int>> ptr;
    message_type<decltype(ptr)> number = 5;

    return 0;
}

我认为你不能做得更好,因为你不允许使用std::shared_ptr 作为非类型模板参数,所以你必须这样做message_type&lt;decltype(ptr)&gt;message_type&lt;ptr&gt; 是不可能实现的(还)。

【讨论】:

  • 我认为这是正确的答案...我会在一段时间后接受它,除非有人要添加更多内容。
猜你喜欢
  • 2015-06-12
  • 2013-10-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-02-20
  • 2011-02-14
  • 1970-01-01
相关资源
最近更新 更多