防止基于模板参数编译功能(或部分)

时间:2015-05-31 00:02:15

标签: 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 statement because it will not compile if T == void */    
    }

   /* Rest if class */
}

如果T == void,我怎么能让编译器知道它不应该编译函数的一部分?我最初尝试使用if语句执行此操作,但它不会编译,因为该部分代码使用<<运算符并使用T类型的变量(这显然是错误的如果T == void)。

2 个答案:

答案 0 :(得分:2)

您无法使用类模板参数来获取成员函数的SFINAE。

您可以为成员函数使用 dummy 模板参数,如下所示:

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)
    {
        // ...
    }
};

See Here

答案 1 :(得分:1)

使用像这样的模板专业化:

#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();
}
相关问题