[嗨,我正在学习c ++,我读了有关is_const之类的类型特征。is_const可以在一行中调用,例如,
cout << is_const<double>::value << endl;
我制作了自己的is_const版本,但测试了变量是否为const,可以像这样使用它,
#include<iostream>
using namespace std;
template<typename T>
struct check_const {
check_const(const T *x): val(std::true_type{})
{ }
check_const(T *x) : val(std::false_type{})
{ }
bool val;
};
int main()
{
const double pi= 3.14;
check_const<double> r(&pi);
cout << r.val << endl; // returns 1
double x= 2.7;
check_const<double> s(&x);
cout << s.val << endl; // returns 0
return(0);
}
我也想在一行中调用check_const,但是编译器不断给我类似错误
"typename not allowed"
当我尝试这样称呼时
cout << check_const<double> t(&pi)::val << endl;
如何更改check_const,以便可以在一行中调用它?
您在这里使用的语法略有错误:
cout << check_const<double> t(&pi)::val << endl;
代替使用
cout << check_const<double>(&pi).val << endl;
check_const<double> t(&pi)
是命名变量的定义的语法,但是表达式中不能包含声明/定义。
check_const<double>(&pi)
是创建未命名临时文件的语法,可以在表达式中完成。
然后您需要.
而不是::
,因为val
是check_const
的非静态成员。
不过,所有这些都可以简化,因为您实际上并没有使用该类。您可以将构造函数用作自由函数:
template<typename T>
constexpr bool check_const(const T *x) { return true; }
template<typename T>
constexpr bool check_const(T *x) { return false; }
([constexpr
使得可以在常量表达式中使用这些函数,但并非必需。)
这可以更容易地用作
cout << check_const(&pi) << endl;
此外,也不要使用指针,而是使用引用:
template<typename T>
constexpr bool check_const(const T &x) { return true; }
template<typename T>
constexpr bool check_const(T &x) { return false; }
您可以写
cout << check_const(pi) << endl;