是否可以從模板引數中捕獲模板,即具有包含模板型別的模板引數的嵌套模板說明符?
template< typename T, typename Label = std::string>
class foo {
// ...
};
template <
template < typename C, typename T > typename C<T>,
// ...
typename Label = std::string
>
class bar {
// ...
C< foo< T, Label > > A;
};
例如,我想將通用 STL 容器 ( std::vector< int >) 作為模板引數傳遞,但宣告具有相同元型別 ( std::vector) 但具有不同值型別 ( foo< int >) 的成員,即std::vector< foo< int > >。這可能看起來很復雜,但不要對 STL 容器的型別進行硬編碼會很有幫助。
對于背景關系,我的目標是提供一些更高級別功能的通用容器配接器/包裝器(在std::stack或行中std::queue)。
uj5u.com熱心網友回復:
是的,您可以只使用模板專業化:
#include <string>
template<typename T, typename Label = std::string>
class foo {};
template <class T, typename Label = std::string>
class bar;
template <template<class...> class C, typename T, typename Label>
class bar<C<T>, Label> {
C<foo<T, Label>> A;
};
演示。
uj5u.com熱心網友回復:
另一個答案的方法可以概括為可重用的模板重新系結器:
template<typename T>
struct rebinder;
template<template<typename...> typename T, typename... Args>
struct rebinder<T<Args...>> {
template<typename... Us>
using rebind = T<Us...>;
};
template<typename T, typename... Us>
using rebound = rebinder<T>::template rebind<Us...>;
// example:
#include <vector>
template<typename T>
struct MyStruct {
rebound<T, float> vec;
};
int main() {
MyStruct<std::vector<int>> x;
static_assert(std::is_same_v<std::vector<float>, decltype(x.vec)>);
}
在Godbolt上看到
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/323578.html
