C++ C++;可变模板部分模板专用化,带有std::enable_if
ITNOA 我的问题是如何在可变模板部分模板专门化场景中使用C++ C++;可变模板部分模板专用化,带有std::enable_if,c++,templates,c++14,variadic-templates,template-meta-programming,C++,Templates,C++14,Variadic Templates,Template Meta Programming,ITNOA 我的问题是如何在可变模板部分模板专门化场景中使用std::enable_if 例如,我有一个使用可变模板部分专门化的类,如下所示 /** *常见情况。 */ 模板 结构foo; /** *foo的最后一个超类。 */ 模板 结构foo{void func(){}; /** *普通的foo课。 */ 模板 结构foo:公共foo{ typedef super-foo; void func(){ coutenable_if是定义type=Tifb==true的类模板。因此,enable_
std::enable_if
例如,我有一个使用可变模板部分专门化的类,如下所示
/**
*常见情况。
*/
模板
结构foo;
/**
*foo的最后一个超类。
*/
模板
结构foo{void func(){};
/**
*普通的foo课。
*/
模板
结构foo:公共foo{
typedef super-foo;
void func(){
coutenable_if
是定义type=T
ifb==true
的类模板。因此,enable_if::type
只有在b==true
时才是有效表达式。SFINAE声明替换失败不是错误。IMHO不禁用if
将是更合适的名称
部分专门化通过对当前解析类型的模式匹配模板来工作。您不能向其中添加新模板参数,因为它将匹配不同的内容。struct foo
仅匹配foo
,如果。
可从H
中扣除,并计算为true
struct foo
不能简单地工作,因为无法从例如foo
推断H
。它必须以某种方式推断enable\u的语义,如果和是积分的H=int
,那么它将精确地解析为foo
,这当然一般来说是无法做到的。
SIMEAE只能应用于过载解决期间考虑的那些部分。第一个和一个您使用的是类模板参数,但正如我前面所说的,这将改变它实际匹配的。另一个选项是模板参数本身。C++不允许类专用化的默认模板参数。通常用于此目的。函数中没有返回值。SFINAE在类主体或其基类中不使用任何内容。我认为当前设置不可能满足您的要求
我将提供一个轻微的重新设计:
#include <iostream>
#include <type_traits>
// Only specifies behaviour for the head part - one T
// Ts... can be ignored, but are required.
// - I left them because I'm not sure whether you want to use them in the real code.
// - But they are required because `foos` use them as base classes and they must be unique.
template<typename T,bool is_integral,typename...Ts>
struct foo_impl;
template<typename T,typename...Ts>
struct foo_impl<T,true,Ts...>
{
void func() {
std::cout << "Hooray Inegral" << std::endl;
}
};
template<typename T,typename...Ts>
struct foo_impl<T,false,Ts...>
{
void func() {
std::cout << "Hi" << std::endl;
}
};
template<typename T,typename...Ts>
using foo = foo_impl<T,std::is_integral<T>::value,Ts...>;
template<typename...Ts>
struct foos;
template<typename H,typename...Ts>
struct foos<H,Ts...> : private foo<H,Ts...>, public foos<Ts...>
{
using head = foo<H,Ts...>;
using tail = foos<Ts...>;
//Only named differently for clarity, feel free to rename it back to 'func'
void rec_func()
{
//If we inherited from foo<H> so this was only this->foo<H>::func() then
//foos<int,int> would have two foo<int> base classes and this call would be ambigious.
this->head::func();
this->tail::rec_func();
}
};
template<> struct foos<>{
void rec_func(){}
};
int main()
{
foos<int,int,char,double> x;
x.rec_func();
}
#包括
#包括
//仅指定头部零件的行为-一个T
//Ts…可以忽略,但是必需的。
//-我留下它们是因为我不确定你是否想在真正的代码中使用它们。
//-但它们是必需的,因为'foos'将它们用作基类,并且它们必须是唯一的。
模板
结构foo_impl;
模板
结构foo_impl
{
void func(){
我不认为这是可以推断的。如果函数中只有专用部分,您可以为专用部分创建帮助函数(或者,在您的示例中std::cout