Search code examples
c++c++11templatesc++17template-argument-deduction

template type deduction of template parameter


I know, that there exists the possibility for automatic type deduction of function templates, given a particular function parameter, but does there also exist such a method for non type template parameters?

Example:

#include <iostream>

template<typename T, T val>
void func_a(void) {
    std::cout << val << std::endl;
}

template<typename T>
void func_b(T val) {
    std::cout << val << std::endl;
}

int main(void) {
    func_a<uint32_t, 42u>();
    //func_a<42u>();    //This line doesn't work
    func_b(42u);
    return 0;
}

So I don't want to give each time the template argument type uint32_t every time, when I call func_a(). Does there such a method exist in C++17 or below?

I am using g++ v.7.3 and c++17.


Solution

  • In C++17, you can use auto:

    template<auto val>
    void func_a(void) {
        std::cout << val << std::endl;
    }
    
    int main(void) {
        func_a<42u>();
        return 0;
    }