[英]C++: Can I use smart pointers with templates?
我有一個抽象的基礎discrete_distribution
distributions
,它有兩個派生類, continuous_distribution
和 Discrete_distribution 。 我有一個帶有unordered_map
的 function make_distribution
,它返回一個指向(連續)分布的智能指針,
std::shared_ptr<continuous_distribution> make_distribution(std::tuple<std::string, float, float> DIST)
{
std::string name = std::get<0>(DIST);
float a = std::get<1>(DIST);
float b = std::get<2>(DIST);
std::unordered_map<std::string,std::shared_ptr<continuous_distribution>> MAP = {
std::make_pair("cauchy", std::make_shared<cauchy>(a, b)),
std::make_pair("exponential", std::make_shared<exponential>(a)),
{...}
};
return MAP[name];
}
由於有兩個派生類,我想知道是否有辦法利用模板編寫單個 function,它返回指向相應分布類型的指針。 我嘗試使用以下內容,
template <class type>
std::shared_ptr<type> make_distribution(std::tuple<std::string, float, float> DIST)
{
std::string name = std::get<0>(DIST);
float a = std::get<1>(DIST);
float b = std::get<2>(DIST);
std::unordered_map<std::string,std::shared_ptr<type>> MAP = {
std::make_pair("cauchy", std::make_shared<cauchy>(a, b)),
std::make_pair("exponential", std::make_shared<exponential>(a)),
{...}
};
return MAP[name];
}
但是,當調用這個 function 時,
int main()
{
std::tuple<std::string, float, float> TARGET{"cauchy", 1, 1};
std::shared_ptr<continuous_distribution> target = make_distribution(TARGET);
}
我收到一個我不太明白的錯誤,
no instance of function template "make_distribution" matches the argument list -- argument types are: (std::tuple<std::string, float, float>)
模板參數只能從調用 function 參數中推導出來,不能從返回類型中推導出來。 function 中的所有參數都不依賴於模板參數,因此不匹配。
在您的情況下,您必須明確指定模板參數,它應該可以工作:
std::shared_ptr<continuous_distribution> target = make_distribution<continuous_distribution>(TARGET);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.