C++模板可以确定声明/定义的实例是否是常量?

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.

  • 我认为问题更多的是构造函数是否可以知道正在构造的实例是否为const.上面的代码将无法检测到这一点,因为在带有`X`的示例中,const是从隐式`this`参数(函数声明的最右边的`const`)推断的,但是不能在构造函数中是`const`. (2认同)