template<typename T> struct foo<typename bar<T>::Type> {
static void func() { ... }
};
你正在使用T
在不可推论的上下文中,因此编译器无法推论T
即使它知道的价值bar<T>::Type
.
假设你写,
foo<double> foodouble;
那么你可能会想,bar
这是专门从事double
实例化时会被选择foo
?仅当编译器可以确保不存在另一种专门化时,这似乎才合理bar
它定义了double
作为嵌套类型,像这样:
template<> struct bar<int> { typedef double Type; };
Now bar<double>::Type
and bar<int>::Type
两者都给予double
。所以底线是:可能存在无限数量的专业化bar
,所有这些都可以提供double
作为嵌套类型,使得编译器无法uniquely推导模板参数bar
类模板。
您可以使用SFINAE http://en.wikipedia.org/wiki/Substitution_failure_is_not_an_error as:
#include <iostream>
template<typename T> struct bar { typedef void type; };
template<> struct bar<float> { typedef bar<float> type; };
template<> struct bar<double> { typedef bar<double> type; };
template<typename T>
struct foo : bar<T>::type
{
static void func()
{
std::cout << "primary template for float and double" << std::endl;
}
};
template<>
struct foo<bool>
{
static void func()
{
std::cout << "specialization for for bool" << std::endl;
}
};
int main()
{
foo<float>::func();
foo<double>::func();
foo<bool>::func();
}
Output (在线演示 http://ideone.com/XVkE3):
primary template for float and double
primary template for float and double
specialization for for bool
注意struct foo : bar<T>::type
不再是一个专业了。它是一个主要模板。另请注意,这可能不是您想要的,因为它会禁用除类型参数之外的类模板的所有实例化float
, double
and bool
;例如,你不能使用foo<int>
。但我还注意到您未定义主模板,因此我希望该解决方案符合您的要求。