简体   繁体   English

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

[英]Deducing Non-Type Template Argument Unsigned Int / size_t

Im trying to deduce a non-type template argument. 我试图推断出非类型模板参数。

#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?
}

But I am getting error: 但我得到了错误:

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>'

Is it possible to deduce the unsigned int, without having to explicitly state the template parameter? 是否可以推断出unsigned int,而不必显式声明template参数?

Id like to have it clean like: getsize(4U) I want to avoid writing: getsize<4U>() 我想像它一样干净:getsize(4U)我要避免写:getsize <4U>()

Thanks alot for any help 非常感谢您的帮助

It is possible to deduce a non-type template argument from function arguments, but not in the way you want. 可以从函数参数中推断出非类型模板参数,但不是您想要的方式。 It can only be deduced from the type of the function argument, not from the value. 它只能从函数参数的类型推导,而不能从值推导。

For example: 例如:

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));

The following code mentions the number 4 a minimal number of times: 以下代码最少提及数字4

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

int main()
{
    getsize<4>();
}

You can't possibly mention the number less than one time. 您最多只能提及一次。

Something wrong with doing this (I think this is what you want??) 这样做有问题(我这就是您想要的??)

#include <iostream>

template<typename Ty>
void getsize(Ty t) { std::cout << t << std::endl; };

int main(int argc, char *argv[])
{
    getsize(4U);
    return 0;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM