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.
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;
}
Given a +1 for the C++17 solution, a better-than-nothing C++11/C++14 solution can be the use of a macro to activate decltype()
over the argument.
By example, with the macro
#define func_a_macro(val) func_a<decltype(val), val>
or better, as suggested by liliscent, to avoid problems with references
#define func_a_macro(val) \
func_a<std::remove_reference<decltype(val)>::type, val>
you can call
func_a_macro(42u)();
ps: I know... I know... macros are distilled evil... but sometime are useful.
C++14 solution with no macros:
template<int N> auto Int = std::integral_constant<int, N>{};
template<class T, T n>
constexpr auto foo(std::integral_constant<T, n> x)
{
std::cout << x.value << std::endl;
}
int main()
{
foo(Int<6>);
}
c++11:
template<int N> using Int = std::integral_constant<int, N>;
template<class T, T n>
constexpr void foo(std::integral_constant<T, n> x)
{
std::cout << x.value << std::endl;
}
int main()
{
foo(Int<6>());
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.