Pat*_*ykB 5 c++ templates class member c++17
有没有一种方法可以确定一个对象在堆上是否至少有一个成员?
我试图能够将像std::stringor std::vectoror这样的对象std::list(是的,主要是容器)与所有其他类型区分开来(不幸的是,即使是具有单个元素的容器也在我的“感兴趣范围”内)
我正在尝试做类似以下的事情:
struct foo
{
private:
int * _ptr;
public:
foo() : _ptr(new int) {};
~foo() { delete _ptr; };
};
struct bar
{
private:
int val;
};
template <typename T>
void func(T val)
{
if constexpr (std::is_class_v<T>)
{
std::cout << std::setw(20) << typeid(T).name() << " is a class type." << std::endl;
if (/* determine if foo has any heap allocations */)
{
// Do something #1.
std::cout << std::setw(20) << typeid(T).name() << " does allocate on heap." << std::endl;
}
else
{
// Do something #2.
std::cout << std::setw(20) << typeid(T).name() << " does NOT allocate on heap." << std::endl;
}
}
else
{
// Do something #3.
std::cout << std::setw(20) << typeid(T).name() << " is NOT a class type." << std::endl;
}
}
int main()
{
func(foo()); // foo does allocate on heap
cout << endl;
func(bar()); // bar does NOT allocate on heap
cout << endl;
};
Run Code Online (Sandbox Code Playgroud)
类foo和bar只是示例,该函数必须执行与控制台func()稍有不同的功能。cout
| 归档时间: |
|
| 查看次数: |
901 次 |
| 最近记录: |