Angew 给出的答案向您展示了正确的方法,但没有向您展示如何处理无法推断且U
必须由实例化客户端提供的情况。V
要处理这种情况,您可以为模板参数U
和分配默认参数V
:
struct D1 { }; struct D2 { };
struct F1 { }; struct F2 { };
// Primary template
template<typename T>
struct deduce_from
{
};
// Specialization for double: U -> D1, V -> D2
template<>
struct deduce_from<double>
{
typedef D1 U;
typedef D2 V;
};
// Specialization for float: U -> F1, V -> F2
template<>
struct deduce_from<float>
{
typedef F1 U;
typedef F2 V;
};
// Give defaults to U and V: if deduce_from is not specialized for
// the supplied T, and U or V are not explicitly provided, a compilation
// error will occur
template<
typename T,
typename U = typename deduce_from<T>::U,
typename V = typename deduce_from<T>::V
>
struct Foo
{
typedef U typeU;
typedef V typeV;
};
这是一个简单的程序来测试上述解决方案的正确性:
#include <type_traits>
int main()
{
static_assert(std::is_same<Foo<double>::typeU, D1>::value, "Error!");
static_assert(std::is_same<Foo<double>::typeV, D2>::value, "Error!");
static_assert(std::is_same<Foo<float>::typeU, F1>::value, "Error!");
static_assert(std::is_same<Foo<float>::typeV, F2>::value, "Error!");
// Uncommenting this will give you an ERROR!
// No deduced types for U and V when T is int
/* static_assert(
std::is_same<Foo<int>::typeU, void>::value, "Error!"
); */
static_assert(
std::is_same<Foo<int, bool, char>::typeU, bool>::value, "Error!"
); // OK
static_assert(
std::is_same<Foo<int, bool, char>::typeV, char>::value, "Error!"
); // OK
}