Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/124.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 防止基于模板参数编译函数(或函数的一部分)_C++_Templates - Fatal编程技术网

C++ 防止基于模板参数编译函数(或函数的一部分)

C++ 防止基于模板参数编译函数(或函数的一部分),c++,templates,C++,Templates,给定一个类,例如 template<typename T = void> class Foo { void Baz() { // Do something regardless of specialization /* Do stuff if the template was specified (i.e. if not void) */ /* This cannot be handled with an if stat

给定一个类,例如

template<typename T = void>
class Foo
{
    void Baz()
    {
        // Do something regardless of specialization
        /* Do stuff if the template was specified (i.e. if not void) */
        /* This cannot be handled with an if statement because it will not compile if T == void */    
    }

   /* Rest if class */
}
模板
福班
{
void Baz()
{
//不分专业做某事
/*如果指定了模板,则执行填充(即,如果不是无效)*/
/*这不能用if语句处理,因为如果T==void*/
}
/*下课休息*/
}

如果
t==void
,如何让编译器知道它不应该编译函数的某个部分?我最初尝试使用一个
if
语句来实现这一点,但它不会编译,因为该代码部分使用
您不能使用类模板参数来获取成员函数的SFINAE

可以对成员函数使用伪模板参数,如下所示:

template<typename T = void>
class Foo
{
   public:
   template <typename Dummy = char>
    void Baz(typename std::enable_if< !std::is_same<T ,void>::value, 
                                 Dummy>::type * = 0)
    {
        // ...
    }
};
模板
福班
{
公众:
模板
void Baz(typename std::enable_如果<!std::is_same::value,
虚拟>::类型*=0)
{
// ...
}
};

像这样使用模板专门化:

#include <iostream>

template<class T>
void BazHelper(){
    // Do something regardless of specialization
    /* Do stuff if the template was specified (i.e. if not void) */
    std::cout << "Not void code\n";
}

template <>
void BazHelper<void>(){
    // Do something regardless of specialization
    /* Do NOT do stuff if the template was specified (i.e. if not void) */
    std::cout << "void code\n";
}

template<typename T = void>
struct Foo{
    void Baz()
    {
        // Do something regardless of specialization
        BazHelper<T>();
        /* Do stuff if the template was specified (i.e. if not void) */
        /* This cannot be handled with an if statement because it will not compile if T == void */
    }

    /* Rest if class */
};

int main(){
    Foo<> vf;
    vf.Baz();
    Foo<double> df;
    df.Baz();
}
#包括
模板
void BazHelper(){
//不分专业做某事
/*如果指定了模板,则执行填充(即,如果不是无效)*/

std::cout谢谢:)我刚刚意识到我传递了函数
Baz
两个参数(都是
unsigned int
)。我如何在你给出的例子中包含这些内容?我试着看看把它们放在论点列表的开头/结尾是否有效,但我错了。谢谢,我决定现在使用给出的其他方法,但我会记住这个方法