mot*_*m79 2 c++ templates c++17 if-constexpr
假设我有一个在其构造函数中使用布尔值的类,并且如果调用不同的函数,则依赖于布尔值.
class MyClass {
MyClass(bool is_second)
{
common_code();
if (!is_second)
first_constructor();
else
second_constructor();
}
};
Run Code Online (Sandbox Code Playgroud)
我是C++ 17的新手,我想知道是否可以使用模板编程来编写这个逻辑if constexpr.api是这样的:
MyClass<> obj_calls_first_const;
MyClass<is_second_tag> obj_calls_second_const;
Run Code Online (Sandbox Code Playgroud)
符合您所需的API:
struct is_second_tag { };
template <typename T = void>
struct MyClass
{
MyClass()
{
if constexpr(std::is_same_v<T, is_second_tag>)
{
second_constructor();
}
else
{
first_constructor();
}
}
};
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
131 次 |
| 最近记录: |