[英]Constexpr alias of overloaded template function
嘗試在特定類類型上為該類的特定構造函數設置make_shared別名。 我最好的嘗試:
class foo { public: foo(int x) : y(x) {} int y; };
constexpr auto newfoo = static_cast<std::shared_ptr<foo>(*)(int)>(std::make_shared<foo>);
產量:
error: invalid static_cast from type ‘<unresolved overloaded function type>’ to type ‘std::shared_ptr<foo> (*)(int)’
constexpr auto newfoo = static_cast<std::shared_ptr<foo>(*)(int)>(std::make_shared<foo>);
我究竟做錯了什么?
std::make_shared
是一個可變參數函數模板 。 您只是將<foo>
指定為模板參數,但是您還需要在某處使用int
。 無論如何,你的方法必然會失敗,因為它依賴於make_shared
的模板參數的布局,並且因為在C ++中使用重載集通常很麻煩。
我建議改為創建一個包裝函數:
constexpr auto newfoo(int x)
{
return std::make_shared<foo>(x);
}
在我看來,它更容易編寫,閱讀和理解。 如果你真的需要SFINAE友好和noexcept
,你可以重復身體三次 :
constexpr auto newfoo(int x)
-> decltype(std::make_shared<foo>(x))
noexcept(noexcept(std::make_shared<foo>(x)))
{ return std::make_shared<foo>(x); }
可以使用宏來減輕上述聲明的痛苦。
如果你真的想要一個函數指針,這似乎工作:
auto newfoo =
static_cast<std::shared_ptr<foo>(*)(const int&)>(
&std::make_shared<foo, const int&>);
看看make_shared
的聲明:
template< class T, class... Args >
shared_ptr<T> make_shared( Args&&... args );
你需要提供T=foo
和Args...
東西Args...
由於Args...
是一個轉發參考包,它總是推導出左值引用或右值引用 。 這就是為什么<foo, const int&>
是一組有效的模板參數而<foo, int>
不是。
正如Zefick在評論中指出的那樣,所有這些都可以簡化為:
constexpr auto newfoo = &std::make_shared<foo, const int&>;
這里不需要演員。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.