c++ - 使用 decltype 返回元素类型的元函数

标签 c++ template-meta-programming decltype

我有以下 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++ 元编程,这甚至可能吗?如果是这样,正确的语法是什么?

最佳答案

这个有效:

#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<decltype(ptr)> , message_type<ptr>无法实现(目前)。

关于c++ - 使用 decltype 返回元素类型的元函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57991984/

相关文章:

c++ - `3n` 不同的元素并找到两个值,`x < y`?

c++ - 如何使用元编程过滤 const 类型和非 const 类型?

c++推导 "non type pointer to function"类模板参数

c++ - 在 C++ 中使用自定义比较函数初始化多重集

c++ - 如何检测无符号整数溢出?

c++ - 光能传递全局照明阴影边缘抖动,不直

c++ - 将 std::cerr 写入 txt 文件

c++ - 使用具有非 constexpr 值的 int 模板函数

c++ - 仅当模板参数不是 const 时才定义 C++ 转换运算符

c++ - 与条件运算符一起使用时 decltype 行为不一致