【问题标题】:Show type of param in template在模板中显示参数类型
【发布时间】:2020-07-02 07:28:14
【问题描述】:

我正在努力解决参考折叠问题(https://www.amazon.com/Effective-Modern-Specific-Ways-Improve/dp/1491903996 上的第 28 项),并且想尝试为模板提供不同的内容。

我用 lvalue 和 ravlue 调用模板,但我没有在模板中看到确切的类型。我怎样才能让编译器在它专门化模板的时候吐出确切的类型?

#include <iostream>
#include <typeinfo>

class Widget{
public:
    int x=0;
};


template<typename T>
void MyMethod(T&& param){
    std::cout << typeid(param).name()<< std::endl; // this just says 6Widget...
};

Widget GetWidget(){
    return Widget();
};

int main() {

    Widget &w1 = * new Widget;
    MyMethod(w1);

    Widget w2;
    MyMethod(w2);

    MyMethod(GetWidget());

    return 0;
}

这只是输出

6Widget
6Widget
6Widget

编译器有什么方法可以准确地找出它为调用模板所做的特化和类型?

【问题讨论】:

    标签: c++ templates rvalue lvalue


    【解决方案1】:

    真的很棒的书。不过好像你已经跳了很多章。

    在第 4 项中,您将看到如何使用 Boost.TypeIndex 做到这一点,其中:

    std::cout << boost::typeindex::type_id_with_cvr<decltype(param)>().pretty_name();
    

    【讨论】:

      猜你喜欢
      • 2019-06-24
      • 1970-01-01
      • 1970-01-01
      • 2021-03-18
      • 1970-01-01
      • 1970-01-01
      • 2019-12-11
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多