推导非类型模板参数 Unsigned Int / size_t

bry*_*mon 4 c++ templates

我试图推断出一个非类型模板参数。

#include <iostream>

template <unsigned int S>
void getsize(unsigned int s) { std::cout << s << std::endl; }

int main()
{
  getsize(4U); 
// Id like to do this without explicitly stating getsize<4U>(4);
// or even getsize<4U>(); 
// Is this possible?
}
Run Code Online (Sandbox Code Playgroud)

但我收到错误:

deduce_szie_t.cpp: In function 'int main()':
deduce_szie_t.cpp:9:15: error: no matching function for call to 'getsize(unsigned int)'
deduce_szie_t.cpp:9:15: note: candidate is:
deduce_szie_t.cpp:4:6: note: template<unsigned int <anonymous> > void getsize(unsigned int)
deduce_szie_t.cpp:4:6: note:   template argument deduction/substitution failed:
deduce_szie_t.cpp:9:15: note:   couldn't deduce template parameter '<anonymous>'
Run Code Online (Sandbox Code Playgroud)

是否可以推导出无符号整数,而不必显式声明模板参数?

我想让它干净如:getsize(4U) 我想避免写作:getsize<4U>()

非常感谢您的帮助

Ste*_*sop 5

可以从函数参数中推导出非类型模板参数,但不是您想要的方式。它只能从函数参数的类型中推导出来,而不能从值中推导出来。

例如:

template <unsigned int S>
void getsize(int (*s)[S]) {
    std::cout << "pointer value: " << (void*)s << std::endl;
    std::cout << "deduced size: " << S << std::endl;
}

getsize(static_cast<int (*)[4]>(0));
Run Code Online (Sandbox Code Playgroud)