小编Dav*_*ets的帖子

为什么从构造函数参数中删除“const”会阻止类被实例化?

从第 12 行删除const可以防止该类What在编译期间被实例化。What无论声明中的常量如何,我都不希望被实例化。这在 clang、gcc 和 MSVC 之间是一致的,所以我认为它是标准的。标记构造函数explicit也不会阻止实例化。我在这里不明白什么?为什么常量会产生影响?

template <typename T> constexpr bool just_false() { return false; }

template<typename T>
class What {
    static_assert(just_false<T>(), "Why was this class instantiated?");
};

struct The {};

struct Heck {
    Heck(The) {}
    Heck(const What<int>&); // Removing 'const' from this line stops 'What<int>' from being instantiated
};

int main() {
    The the;
    Heck{the};
}
Run Code Online (Sandbox Code Playgroud)

just_false咒语只是为了防止静态断言始终触发,无论实例化如何。

编译器浏览器链接:https ://godbolt.org/z/8cETcfss5

c++ constructor c++17

34
推荐指数
2
解决办法
3748
查看次数

标签 统计

c++ ×1

c++17 ×1

constructor ×1