Search code examples
c++templatestemplate-argument-deduction

Use one argument for template parameter deduction?


Let’s say I have a template function, assign(). It takes a pointer and a value and assigns the value to the pointer’s target:

template <typename T> void assign(T *a, T b) { *a = b; }

int main() {
    double i;
    assign(&i, 2);
}

In this case I always want T to be deduced from the first argument, but it looks like I didn’t do a good job of expressing this. 2’s type is int, so:

deduce.cpp:5:5: error: no matching function for call to 'assign'
    assign(&i, 2);
    ^~~~~~
deduce.cpp:1:28: note: candidate template ignored: deduced conflicting types for parameter 'T' ('double' vs. 'int')
template  void assign(T *a, T b) { *a = b; }

Is there a way I can declare assign() so that the second argument doesn’t participate in template parameter deduction?


Solution

  • C++20 has std::type_identity which can be used to establish a non-deduced context:

    #include <type_traits>
    
    template <typename T>
    void assign(T *a, std::type_identity_t<T> b) {
        *a = b;
    }
    
    int main() {
        double i;
        assign(&i, 2);
    }
    

    Demo