有沒有辦法在沒有部分模板特化的情況下,確定一個類模板化的模板引數的模板引數,假設一個類只能用一個模板引數模板化,而模板引數本身就是一個模板?
為了使事情具體化,這里有一個例子:
template <typename T>
struct A {
// Needed: a function to print the size of the template parameter
// that "T" is templatized with, e.g. "char" in the example
// below
};
template <typename A>
struct X{}
int main() {
A<X<char>>
}
uj5u.com熱心網友回復:
正是在這種情況下,標準容器會暴露一個value_type成員,例如:
template <class T>
struct A {
// Needed: a function to print the size of the template parameter
// that "T" is templatized with, e.g. "char" in the example
// below
void printSize() const { cout << sizeof(typename T::value_type); }
};
template <typename A>
struct X {
using value_type = A;
};
在線演示
否則,您可以使用一個單獨的幫助程式,該幫助程式利用模板模板引數和模板引數推導來確定值型別是什么,例如:
template<template<class, class...> class C, class T, class... OtherTs>
size_t A_helper_printSize(C<T, OtherTs...>&&) { return sizeof(T); }
template <class T>
struct A {
// Needed: a function to print the size of the template parameter
// that "T" is templatized with, e.g. "char" in the example
// below
void printSize() const { cout << A_helper_printSize(T{}); }
};
在線演示
或者:
template<template<class, class...> class C, class T, class... OtherTs>
T A_helper_valueType(C<T, OtherTs...>&&);
template <class T>
struct A {
// Needed: a function to print the size of the template parameter
// that "T" is templatized with, e.g. "char" in the example
// below
void printSize() const { cout << sizeof(decltype(A_helper_valueType(std::declval<T>()))); }
};
在線演示
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/447274.html
上一篇:如何在類模板中多載函式模板函式?
