减少C++中模板类参数的数量

4

I have a class like this:

template <unsigned int A, unsigned int B>
class Foo { ... };

Foo需要一个名为bar()的方法,但我需要特别处理它。例如,当A == B时,我希望它做一件事情,否则做其他事情。我能否在不将if语句写入函数的情况下实现这一点?像这样:

Foo<A, A>::bar() { ... } and Foo<A, B>::bar() { ... }

部分类特化对你没有帮助吗? - SergeyA
标记调度也可能有所帮助。 - Jarod42
2个回答

5
您可以部分特化您的类:
#include<cassert>

template<typename A, typename B>
struct S {
    void f(int i) { assert(i == 42); }
};

template<typename A>
struct S<A, A> {
    void f(int i) { assert(i == 0); }
};

int main() {
    S<int, double> s1;
    S<int, int> s2;
    s1.f(42);
    s2.f(0);
}

我不知道我能做到这个。谢谢! - Peter Lenkefi

3
另一种解决偏特化的方法是使用enable_if。我已经假设您具有整数模板参数,但如果您有类型,则可以使用std::is_same<TA,TB>
此答案基于此处的解决方案:std::enable_if to conditionally compile a member function http://coliru.stacked-crooked.com/a/692fbfff1b9d84e8
#include <iostream>
#include <string>

template <unsigned int A, unsigned int B>
class Foo { 
    public:

        template<unsigned int TA=A, unsigned int TB=B>
        typename std::enable_if< TA == TB >::type
        bar() {
         std::cout << "equal version = " << A << "  " << B << "\n";
        }

        template<unsigned int TA=A, unsigned int TB=B>
        typename std::enable_if< TA != TB >::type
        bar() {
         std::cout << "NON equal version = " << A << "  " << B << "\n";
        }
};

int main()
{
    Foo<1, 1> f1;
    f1.bar();

    Foo<1, 2> f2;
    f2.bar();    
    return 0;
}

输出:

equal version = 1  1
NON equal version = 1  2

类型化的模板参数示例如下:

http://coliru.stacked-crooked.com/a/05d6a93480e870aa

#include <iostream>
#include <string>

template <typename A, typename B>
class Foo { 
    public:

        template<typename TA=A, typename TB=B>
        typename std::enable_if<std::is_same<TA, TB>::value>::type
        bar() {
         std::cout << "equal version" << "\n";
        }

        template<typename TA=A, typename TB=B>
        typename std::enable_if<!std::is_same<TA, TB>::value>::type
        bar() {

         // This will cause compilation error if this bar() overload is to be instantiated
         // but since it is not there is no compilation error
         typename TA::non_exists ii = 0;
         std::cout << "NON equal version" << "\n";
        }
};
int main()
{
    Foo<int, int> f1;
    f1.bar();

    //Foo<int, float> f2;
    //f2.bar();    
    return 0;
}

如果我只有相等的版本,那么只有它会被声明吗? - Peter Lenkefi
@PeterLenkefi 编译器应只实例化已使用的函数。 - marcinj

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接