此表單模板模板參數只允許在C++ 17:
template < // v---------- typename here not allowed
template <typename> typename TT,
typename T,
std::enable_if_t<std::is_same<TT<T>, Foo<T>>::value, int> = 0
>
Foo<T> create() {
return Foo<T>(T());
}
您必須更換typename
指出的class
:
template < // v---------- class allowed
template <typename> class TT,
typename T,
std::enable_if_t<std::is_same<TT<T>, Foo<T>>::value, int> = 0
>
Foo<T> create() {
return Foo<T>(T());
}
在C++ 17,這兩個編譯和等同。
爲了讓你的語法Foo<int> foo = create<Foo<int>>();
工作,你只需要做到這一點:
template <typename T>
T create() {
return T{};
}
如果要限制可以發送什麼類型的,你必須創建一個類型特點:
// default case has no typedef
template<typename>
struct first_param {};
// when a template is sent, define the typedef `type` to be equal to T
template<template<typename> class TT, typename T>
struct first_param<TT<T>> {
using type = T;
};
// template alias to omit `typename` everywhere we want to use the trait.
template<typename T>
using first_param_t = typename first_param<T>::type;
然後,用你的特質:
template <
typename T,
void_t<first_param_t<T>>* = nullptr
> // ^---- if the typedef is not defined, it's a subtitution error.
T create() {
return T(first_param_t<T>{});
}
您可以實現void_t
這樣的:
template<typename...>
using void_t = void;
Live at Coliru
所以,實質上,你需要一個'create'函數,它只需要一個'Foo'作爲模板類型並返回一個'Foo '? –
NathanOliver
不能簡單地是'美孚富= createFoo ();' - 作爲構造類型永遠是'美孚'呢? –
axalis
@axalis是的,我可以做'createFoo()',而不是'創建>()',但是我正在尋找我可以概括爲其他類型的解決方案,例如'創建>' –
Daskie