我无法理解非类型模板参数,并希望有人能够阐明这一点。
#include <iostream>
template<typename T, int a>
void f() {
if (a == 1) {
std::cout << "Hello\n";
} else {
T("hello");
}
}
int main() {
f<int, 1>;
}
当我编译这个时,我收到一条错误消息:
/tmp/conditional_templates.cc:13:12: required from here
/tmp/conditional_templates.cc:8:5: error: cast from ‘const char*’ to ‘int’ loses precision [-fpermissive]
T("hello");
^
但是,编译器不能检测到非类型参数“a”为 1,因此不会采用 else 分支吗?还是期望太高了?在这种情况下,我该如何完成这样的事情?
我不得不承认,老实说,我不明白这样做的根本原因,但它是你的代码。除了明显的错误(未能为函数调用提供括号)main()
,以及警告(将字符地址转换为数据丢失int
),关于条件包含的更大问题很重要。
如果您有如下代码:
if (something)
{
do something
}
它显然必须编译,并且会not有条件地这样做。那something
源自非类型模板参数没有区别。您需要将逻辑从函数内的 if 表达式中取出并放入模板扩展控制机制中。专业化就是这样一种技术,SFINAE http://en.wikipedia.org/wiki/Substitution_failure_is_not_an_error是另一个:
#include <iostream>
#include <iomanip>
#include <type_traits>
#include <cstdint>
static const char* something = "something";
template<class T, bool a>
typename std::enable_if<a>::type f()
{
std::cout << __PRETTY_FUNCTION__ << '\n';
std::cout << something << '\n';
}
template<class T, bool a>
typename std::enable_if<!a>::type f()
{
std::cout << __PRETTY_FUNCTION__ << '\n';
std::cout << std::hex << T(something) << '\n';
}
int main()
{
f<int, true>();
f<intptr_t, false>();
}
Output
typename std::enable_if<a>::type f() [T = int, a = true]
something
typename std::enable_if<!a>::type f() [T = long, a = false]
100001f18
您在每个项目中做什么取决于您。当然,您可以使用预处理器宏进行投注并完成大部分/所有这些工作,但是这有什么乐趣呢?
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)