不带任意参数的c ++函数模板 [英] c++ function templates with not arbitrary parameters

查看:179
本文介绍了不带任意参数的c ++函数模板的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑这个工作正常的c ++代码:

  template< size_t N& 
int check(std :: array< unsigned char,N> buf){
std :: cout< N< - << buf.size()<< std :: endl;
return 0;
}


int main(int argc,char * argv [])
{
std :: array< unsigned char,20>一个;
std :: array< unsigned char,30> b;
std :: array< unsigned char,40> C;

check(a);
check(b);
check(c);

return 0;
}

可以显式实例化检查N = 20和N = 30,但是禁用任何其他隐式实例化?



这意味着如果我使用check(c)

编辑:



事实上我想有相同的实现,所以一个模板是正确的选择,我想只是有一个编译时错误,如果由于某种原因我实例化它的参数不应该存在。
因为static_assert(c ++ 11)解决方案看起来是最好的,完全的问题,非常人类可读。

N ,则可以使用 static_assert 引发编译时错误。是除20或30之外的任何值。

  template< size_t N> 
int check(std :: array< unsigned char,N> buf)
{
static_assert(N == 20 || N == 30,N必须是20或30 );

std :: cout<< N< - << buf.size()<< std :: endl;

return 0;
}


Consider this c++ code that works fine:

template <size_t N>
int check(std::array<unsigned char, N> buf){
    std::cout << N << "-" << buf.size() << std::endl;
    return 0;
}


int main (int argc, char *argv[])
{
    std::array<unsigned char, 20> a;
    std::array<unsigned char, 30> b;
    std::array<unsigned char, 40> c;

    check(a);
    check(b);
    check(c);

    return 0;
}

Is it possible to explicitly instantiate "check" for N=20 and N=30, but disable any other implicit instantiation?

That means that I would like to get a compile time error if I use "check(c)",

Edit:

In fact I wanted to have the same implementation, so a template was the right choice, and I wanted to just have a compile time error if for some reason I instantiate it with a parameters that is not supposed to exist. Because of that the static_assert (c++11) solution looks the best, as complete for the problem and very human readable.

解决方案

You can use static_assert to throw a compile time error if N is anything other than 20 or 30.

template <size_t N>
int check(std::array<unsigned char, N> buf) 
{
    static_assert(N == 20 || N == 30, "N must be 20 or 30.");

    std::cout << N << "-" << buf.size() << std::endl;

    return 0;
}

这篇关于不带任意参数的c ++函数模板的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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