提问人:Mad Physicist 提问时间:11/12/2023 更新时间:11/12/2023 访问量:70
使用从模板继承的声明的构造函数的正确语法 [duplicate]
Correct syntax for constructor using declaration inherited from a template [duplicate]
问:
我在命名空间中有一个模板化基类(不确定这是否相关,因此请包含它以防万一)。我正在尝试使用构造函数的声明扩展类,并调用以下方法之一: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)} {}
| ^
如何在扩展中使用模板化基类,以便可以重用基构造函数并调用方法?
答: 暂无答案
评论
this->getP()
就是你要找的。using Test::Base::Base;
也有效,并且当有很多论点要重复时,它就不那么麻烦了。ns::