What is std::decay and when it should be used?

后端 未结 2 819
说谎
说谎 2020-11-30 16:51

What are the reasons for the existence of std::decay? In what situations is std::decay useful?

2条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-11-30 17:13

    When dealing with template functions that take parameters of a template type, you often have universal parameters. Universal parameters are almost always references of one sort or another. They're also const-volatile qualified. As such, most type traits don't work on them as you'd expect:

    template
    void func(T&& param) {
        if (std::is_same::value) 
            std::cout << "param is an int\n";
        else 
            std::cout << "param is not an int\n";
    }
    
    int main() {
        int three = 3;
        func(three);  //prints "param is not an int"!!!!
    }
    

    http://coliru.stacked-crooked.com/a/24476e60bd906bed

    The solution here is to use std::decay:

    template
    void func(T&& param) {
        if (std::is_same::type,int>::value) 
            std::cout << "param is an int\n";
        else 
            std::cout << "param is not an int\n";
    }
    

    http://coliru.stacked-crooked.com/a/8cbd0119a28a18bd

提交回复
热议问题