【问题标题】:How to use variable templates to compare the types of variables in C++ 17?如何使用变量模板来比较 C++ 17 中的变量类型?
【发布时间】:2019-12-22 15:44:20
【问题描述】:

我有一段漂亮的代码,它使用C++14s variable templates

#include <typeinfo>

template<typename T, typename U> 
constexpr bool same_type = false; 

template<typename T> 
constexpr bool same_type<T,T> = true; 

int main() {
    bool f = same_type<int, bool>; // compiles. Evals to false.
    bool t = same_type<int, int>; // compiles. Evals to true.
    int a; 
    int b;
    return same_type<typeid(a), typeid(a)>; // does not compile.
}

它检查两种类型是否相同。我喜欢这个,但是如果我必须自己传递类型而不是从某些变量中派生它们,这对我来说似乎毫无用处。

有没有办法让它工作?我本来预计像 typeid(x) 这样的东西可能会成功。

【问题讨论】:

    标签: c++ types c++14 typeid variable-templates


    【解决方案1】:

    same_type&lt;decltype(a), decltype(a)&gt;.

    注意标准库已经有这个特性,它叫做std::is_same_v&lt;...&gt;

    【讨论】:

    • 真丢脸。我应该对此进行更好的研究
    猜你喜欢
    • 2018-03-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-02-08
    • 2012-09-19
    • 2017-11-27
    相关资源
    最近更新 更多