3
是否可以将is_const
表达式转换为test
函数,或者这是不可能的,因为顶级cv-qualifieres在模板类型推理期间被忽略?is_const <func-param> in函数模板总是返回false
int main()
{
using std::is_const;
const int x = 0;
int y = 0;
// move to "bool test()"
std::cout
<< "main, x: " << is_const<decltype(x)>::value << "\n" // true
<< "main, y: " << is_const<decltype(y)>::value << "\n" // false
;
std::cout
<< "test, x: " << test(x) << "\n" // false, I wanted true
<< "test, y: " << test(y) << "\n" // false
;
}
我已经尝试过失败类似于各种版本:我想确保我不缺少的东西,并且写这样一个test
功能确实不可能
template<typename T>
bool test(T x)
{
return is_const<???>::value;
}
。 (如果有可能,我也想知道C++ 03版本是否是可能的。)
谢谢您的考虑
更新
由于Mankarse我了解到型扣在右值引用的情况不同:
template<typename T> void t1(T x);
template<typename T> void t2(T& x);
template<typename T> void t3(T&& x);
const int x = 42;
int y = 0;
t1(x); // T = int: t1<int>(int x)
t1(y); // T = int: t1<int>(int x)
t2(x); // T = const int: t2<const int>(const int& x)
t2(y); // T = int: t2<int>(int& x)
t3(x); // T = const int&: t3<const int&>(const int& && x)
t3(y); // T = int&: t3<int&>(int& && x)
您的意思是'布尔测试(T && X )'完美转发? (如果模板函数的参数不是引用类型,则在确定其类型时不考虑顶级cv-qualifiers。) –
'typename T :: value_type'? – maverik