gpt4 book ai didi

c++ - 奇怪的循环模板模式 (CRTP) 和派生的构造函数参数

转载 作者:太空宇宙 更新时间:2023-11-04 13:39:13 24 4
gpt4 key购买 nike

我正在使用奇怪的重复模板模式以下列方式(如下)创建共享指针。在 Derived::create(...) 上,Visual Studio IntelliSense 显示可用参数是 (Args &&...args)。如何将派生类构造函数参数列表传递给 Base,以便 IntelliSense 向我显示可用参数是 (const std::string &str, int i)?

#include <memory>
#include <string>

template<typename T>
class Base
{
public:
template<typename... Args >
static std::shared_ptr<T> create(Args&&... args)
{
return std::make_shared<T>(std::forward<Args>(args)...);
}
};

class Derived : public Base<Derived>
{
public:
Derived(const std::string &str, int i) {}
};

int main()
{
auto derived = Derived::create("text", 123);
}

最佳答案

"How to pass Derived class constructor argument list to Base so that IntelliSense would show me that available arguments are (const std::string &str, int i)?"

#include <string>
#include <memory>

template<typename T>
class Base {
public:
template<typename... Args >
static std::shared_ptr<T> create(Args&&... args) {
return std::make_shared<T>(std::forward<Args>(args)...);
}
};

class Derived : public Base<Derived> {
public:
Derived(const std::string &str, int i) {}
};

int main() {
auto derived = Derived::create("text", 123);
}

嗯,你的code just compiles fine .

任何 IDE 的 Intellisense 功能总是与用于它们的 c++ 解析器一样好。这完全取决于实际使用的 IDE,您不应该根据 IDE 的功能来定位您的设计,而是编译和运行良好的内容。

关于c++ - 奇怪的循环模板模式 (CRTP) 和派生的构造函数参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28387303/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com