推导非类型模板参数无符号整数/size_t

4

我正在尝试推导出一个非类型模板参数。

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

但是我遇到了错误:
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>'

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

我希望它像这样简洁:getsize(4U) 我想避免编写:getsize<4U>()

非常感谢任何帮助


1
从什么方面推断呢? - Kerrek SB
从函数参数 getsize(4U) 推断出无符号整数模板参数。 - bryan sammon
2
这没有意义。您不能从函数参数这样的动态量中推断出静态信息(模板参数)。 - Kerrek SB
@bryan:你只是对语法感到不满,对吧?你只想写getsize(4)而不是getsize<4>()?C++不允许你这样做,但如果这对你很重要,你可以编写一个宏;-) - Steve Jessop
1
请注意,代码中没有任何内容表明 Ss 有关联,因此没有理由推断任何事情。 - GManNickG
显示剩余3条评论
3个回答

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

2
以下代码最少次数提到数字4:
template <unsigned int N>
void getsize()
{
    std::cout << N << std::endl;
}

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

您不能不提及数字少于一次。

2

这样做似乎有些问题(我认为这是你想要的??)

#include <iostream>

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

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接