eva*_*eer 3 c++ templates c++11
例如,对于给定的模板,模板std::string
可以检测string
声明/定义的实例是否为常量.(注意:我不是在询问模板参数.)
std::string mutable_string("a string that may possibly be changed");
Run Code Online (Sandbox Code Playgroud)
与
const std::string immutable_string("a string that will not change);
Run Code Online (Sandbox Code Playgroud)
如果可以,模板可以为提供给构造函数的字符串文字准确分配堆存储量.此外,可以省略非const,非ctor/dtor方法的代码生成(除非某些转换单元定义了非const字符串).
我希望在语义上类似于:
is_constant<std::string>(*this)::value
Run Code Online (Sandbox Code Playgroud)
是否可以将实例的类型与剥离的const限定符进行比较?
更新/澄清:扩展std::string
示例,可以模板专业化,const std::string
以便能够将检查员声明为constexpr
(例如size()
,capacity()
?
小智 5
如果我找对你:
#include <iostream>
template <typename T>
inline constexpr bool is_constant(T&) {
return false;
}
template <typename T>
inline constexpr bool is_constant(const T&) {
return true;
}
template <bool Value>
void print() {
std::cout << (Value ? "true " : "false ");
}
struct X {
void a() { print<is_constant(*this)>(); }
void b() const { print<is_constant(*this)>(); }
};
int main() {
X x;
// false
x.a();
// true
x.b();
std::cout << '\n';
return 0;
}
Run Code Online (Sandbox Code Playgroud)
但是,如果要检测对象是否为const限定,则不可能 - 构造函数永远不是const.