使用从模板继承的声明的构造函数的正确语法 [duplicate]

Correct syntax for constructor using declaration inherited from a template [duplicate]

提问人:Mad Physicist 提问时间:11/12/2023 更新时间:11/12/2023 访问量:70

问:

我在命名空间中有一个模板化基类(不确定这是否相关,因此请包含它以防万一)。我正在尝试使用构造函数的声明扩展类,并调用以下方法之一:using

#include <iostream>
#include <memory>

namespace ns
{

template <typename T>
class Base
{
public:
    Base(const std::shared_ptr<const T> x): p{std::move(x)} {}
    Base(const T &x): Base{std::shared_ptr<const T>(&x)} {}
    Base(T &&x): Base{std::make_shared<const T>(std::move(x))} {}

    T getP() { return *p; }
private:
    std::shared_ptr<T> p;
};

} // ns

template <typename T>
class Test : public ns::Base<T>
{
public:
    using ns::Base::Base;

    void print()
    {
        std::cout << getP() << std::endl;
    }
};

int main()
{
    Test<int> t{3};
    t.print();
}

鉴于,我收到以下错误:using ns::Base::Base;

snip.cpp:26:15: error: ‘template<class T> class ns::Base’ used without template arguments
   26 |     using ns::Base::Base;
      |               ^~~~

将其更改为通过构造函数行,但找不到方法的定义:using ns::Base<T>::Base;

snip.cpp: In member function ‘void Test<T>::print()’:
snip.cpp:30:22: error: there are no arguments to ‘getP’ that depend on a template parameter, so a declaration of ‘getP’ must be available [-fpermissive]
   30 |         std::cout << getP() << std::endl;
      |                      ^~~~
snip.cpp:30:22: note: (if you use ‘-fpermissive’, G++ will accept your code, but allowing the use of an undeclared name is deprecated)
snip.cpp: In instantiation of ‘ns::Base<T>::Base(std::shared_ptr<const _Tp>) [with T = int]’:
snip.cpp:13:62:   required from ‘ns::Base<T>::Base(T&&) [with T = int]’
snip.cpp:26:24:   required from here
snip.cpp:11:59: error: no matching function for call to ‘std::shared_ptr<int>::shared_ptr(<brace-enclosed initializer list>)’
   11 |     Base(const std::shared_ptr<const T> x): p{std::move(x)} {}
      |                                                           ^

如何在扩展中使用模板化基类,以便可以重用基构造函数并调用方法?

C++ 模板 继承

评论

1赞 Sam Varshavchik 11/12/2023
this->getP()就是你要找的。
0赞 Mad Physicist 11/12/2023
@SamVarshavchik。这非常有效。不是在嘴里看礼物马,但为什么呢?
1赞 StoryTeller - Unslander Monica 11/12/2023
using Test::Base::Base;也有效,并且当有很多论点要重复时,它就不那么麻烦了。
1赞 StoryTeller - Unslander Monica 11/12/2023
至于访问依赖基地的规范 stackoverflow.com/questions/4643074/......
1赞 JaMiT 11/12/2023
“不确定这是否相关”——不难发现它是否相关。从示例中删除命名空间,对其进行编译,然后查看错误是否仍然存在。如果是这样,则命名空间不是必需的。如果没有,并且您没有错过删除 ,那么它是相关的。ns::

答: 暂无答案