template<class Derived>
struct Base {
void name() {
(static_cast<Derived*>(this))->impl();
}
};
struct D1 : public Base<D1> {
void impl() {
std::cout << "D1::impl()\n";
}
};
struct D2 : public Base<D2> {
void impl() {
std::cout << "D2::impl()\n";
}
};
struct D3 {
void impl() {
std::cout << "D3::impl()\n";
}
};
template <class T>
void myFunction(T value) {
if constexpr (std::is_same_v<T, D1>) {
// Code for float case
std::cout << "D1 constexpr" << std::endl;
value.name();
}
else {
std::cout << "no D1 constexpr" << std::endl;
// Code for general case
}
}
文章展示了C++中如何使用模板和constexpr特性,通过`Base`模板结构和`D1`,`D2`,`D3`子类,以及`myFunction`函数来区分不同类型的调用。如果传入的是`D1`类型,会执行特殊的`impl()`函数并标记为constexpr。
955

被折叠的 条评论
为什么被折叠?



