优雅的模板专业化 [英] Elegant template specialization

查看:89
本文介绍了优雅的模板专业化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有一种基于其模板参数专门化模板的优雅方法吗?

Is there an elegant way to specialize a template based on one of its template parameters?

Ie。

template<int N> struct Junk {
    static int foo() {
        // stuff
        return Junk<N - 1>::foo();
    }
};

// compile error: template argument '(size * 5)' involves template parameter(s)
template<int N> struct Junk<N*5> {
    static int foo() {
        // stuff
        return N;
    }
};

template<> struct Junk<0> {
    static int foo() {
        // stuff
        return 0;
    }
};

我试图专门化一个模板基于参数可被5整除。我唯一的方法,我似乎这样做是如下:

Ie. I am trying to specialize a template based on the parameter being divisible by 5. The only way I can seem to do it is like below:

template<int N> struct JunkDivisibleBy5 {
    static int foo() {
        // stuff
        return N;
    }
};

template<int N> struct Junk {
    static int foo() {
        // stuff
        if ((N - 1) % 5 == 0 && N != 1)
            return JunkDivisibleBy5<N - 1>::foo();
        else
            return Junk<N - 1>::foo();
    }
};


template<> struct Junk<0> {
    static int foo() {
        // stuff
        return 0;
    }
};

但是这显得不那么优雅,并且还需要实例化所有模板,即使模板参数

But this is significantly less elegant, and also necessitates instantiation of all templates even if the template argument shouldn't require it.

推荐答案

如何:

#include <iostream>
using namespace std;

template < typename T, T N, T D >
struct fraction {
    typedef T value_type;
    static const value_type num = N;
    static const value_type denom = D;
    static const bool is_div = (num % denom == 0);
};

template< typename T, T N, T D, bool P >
struct do_if {
    static void op() { cout << N << " NOT divisible by " << D << endl; }
};

template< typename T, T N, T D >
struct do_if< T, N, D, true > {
    static void op() { cout << N << " divisible by " << D << endl; }
};

template < int N >
void foo() {
    typedef fraction< int, N, 5 > f;
    do_if< typename f::value_type, f::num, f::denom, f::is_div >::op();
}

int main() {
    foo< -5 >();
    foo< -1 >();
    foo< 0 >();
    foo< 1 >();
    foo< 5 >();
    foo< 10000005 >();
    return 0;
}

这篇关于优雅的模板专业化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆