[英]Is there a way to name a type for a function template specialization?
例如,当我们有一个通用函数模板时,我们可以在函数中使用模板类型:
template <typename T>
void foo()
{
T t;
...
}
现在,想象一下这个函数模板的特化:
template <>
void foo<MySpecialType>()
{
T t; // Does not compile, no knowledge of formal template argument T
MySpecialType t2; // This is OK, but I have to mention MySpecialType again
}
template <>
void foo<MySpecialType2>()
{
T t; // Does not compile, no knowledge of formal template argument T
MySpecialType2 t2; // This is OK, but I have to mention MySpecialType2 again
}
请注意,在上面的两个特化中,我必须提到函数体内名称专用的模板参数的类型。 我更喜欢使用更通用的占位符(即T),而不是在函数模板特化的主体内重复专门的类型(可能是多次)。
如果有一种方法可以在实际的特化功能定义中使用T或创建一个别名,那就太棒了。 我知道我可以通过实际函数体内的类型别名来做到这一点:
template<>
void foo<MySpecialType>
{
using T=MySpecialType; // But then I still repeat the type at least once
...
我更喜欢专业化的约定,如:
// Warning: Not valid C++
template<>
void foo<T=MySpecialType>
{
T t;
...
要么:
// Warning: Not valid C++
template<T>
void foo<MySpecialType>
{
T t;
...
谢谢你的建议。
你可以这样做:
template <typename T>
struct bar
{
using Type = T;
static void foo();
};
template <typename T>
void bar<T>::foo()
{
Type t;
// ...
}
template <>
void bar<MySpecialType>::foo()
{
Type t;
// ...
}
template <>
void bar<MySpecialType2>::foo()
{
Type t;
// ...
}
template <typename T>
void foo()
{
bar<T>::foo();
}
但你真的需要它吗?
这是可行的。 以下是一个使用部分特化的工作解决方案,因此包含静态函数的类模板:
template<typename T, typename U = void>
struct foo_impl
{
static void bar()
{
::std::cout << "T\n";
}
};
template<typename T>
struct foo_impl<T, typename ::std::enable_if<::std::is_same<T, int>::value>::type>
{
static void bar()
{
::std::cout << "int\n";
}
};
template<typename T>
void foo()
{
foo_impl<T>::bar();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.