【问题标题】:Type inference for integral template parameter积分模板参数的类型推断
【发布时间】:2016-04-11 07:15:20
【问题描述】:

我创建了一个拥有方法唯一标识的类型

template <typename Method, Method method>
struct identity {
};

所以我可以以独特的方式描述方法,即使它们具有相同的签名

struct Class {
    void foo() {}
    void bar() {}
};

typedef identity<decltype(&Class::foo), &Class::foo> foo_identity;
typedef identity<decltype(&Class::bar), &Class::bar> bar_identity;

std::cout << std::boolalpha << std::is_same<foo_identity, bar_identity>::value << std::end;
// prints "false"

由于实例化的方法过于冗长,因为两个名称都被使用了两次,所以可以将其缩短为:

#define GEN_IDENTITY(NAME) identity<decltype(&NAME), &NAME>
GEN_IDENTITY(Class::foo)

但是有没有办法在不使用宏的情况下推断它?或者也许还有其他方法可以得到一个可以明确描述方法的类型?

【问题讨论】:

    标签: c++ c++11 c++14


    【解决方案1】:

    但是有没有办法不使用宏来推断它?

    目前,没有。有一个建议在语言中添加一个构造,这将使非类型模板参数可以扣除,就像auto (N4469)

    但现在,您可以用它来简化身份:

    template<typename T, T t>
    using identity = std::integral_constant<T, t>;
    

    【讨论】:

    • 好的,感谢您提供的提案链接。希望它在某个时候被添加到标准中。
    猜你喜欢
    • 2023-03-31
    • 2015-02-06
    • 2018-07-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多