【发布时间】:2020-03-10 23:50:26
【问题描述】:
假设我有一个由引擎参数化的struct 模板S:
template<class Engine> struct S;
我有两个引擎:一个带有constexpr 成员函数size() 的“静态”引擎,以及一个带有非constexpr 成员函数size() 的“动态”引擎:
struct Static_engine {
static constexpr std::size_t size() {
return 11;
}
};
struct Dynamic_engine {
std::size_t size() const {
return size_;
}
std::size_t size_ = 22;
};
如果引擎的size() 是constexpr,我想在S 中定义可以用作constexpr 的size() 成员函数。我写:
template<class Engine>
struct S {
constexpr std::size_t size() const {
return engine_.size();
}
Engine engine_;
};
然后下面的代码用 GCC、Clang、MSVC 和 ICC 编译:
S<Static_engine> sta; // not constexpr
S<Dynamic_engine> dyn;
constexpr auto size_sta = sta.size();
const auto size_dyn = dyn.size();
考虑到constexpr 的复杂性和各种“格式错误,不需要诊断”,我仍然有一个问题:这段代码格式正确吗?
【问题讨论】:
-
"格式错误,不需要诊断" 关于
constexpr函数的内容并不多。如果你试图滥用他们的constexpr状态,编译器必须是嘈杂的。
标签: c++17 c++20 c++ c++17 constexpr c++20