When to use the “identity” tmp trick?

前端 未结 2 893
感情败类
感情败类 2020-12-13 20:15

I have seen this meta function used, but never really understod why and in what context it is required. Can someone explain it with an example?

template <         


        
2条回答
  •  伪装坚强ぢ
    2020-12-13 21:06

    It introduces a non-deduced context, when deducing template arguments from function parameters. For example, say you have a function with the following signature :

    template 
    void foo(T a, T b);
    

    If someone were to call foo(123L, 123), they'd get a substitution error, as T cannot match long int and int at the same time.

    If you want to match only the first argument, and convert the other one implicitly if needed, you can use identity :

    template 
    void foo(T a, typename identity::type b);
    

    Then b does not participate in type deduction, and foo(123L, 123) resolves to foo(123L, 123).

提交回复
热议问题