禁止特定功能模板实例化 [英] Disallow a specific function template instantiation

查看:150
本文介绍了禁止特定功能模板实例化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想定义一个模板函数,但不允许使用特定类型的实例化。请注意,一般来说,所有类型都是允许的,通用模板可以工作,我只想禁止使用几种特定类型。



例如,防止对模板使用 double 。这不会实际上阻止实例化,而只是通过不定义函数而导致链接器错误。

  template< typename T> ; 
T convert(char const * in)
{return T(); }

//这种方式创建一个链接器错误
template<>
double convert< double>(char const * in);

int main()
{
char const * str =1234;

int a = convert< int>(str);
double b = convert< double>(str);
}

代码只是一个演示,显然convert函数必须

问题:在上面的代码中,如何在尝试使用<$ c时产生编译器错误$ c> convert< double> 实例化?






如何有意地导致编译时错误模板实例化它处理一个类,而不是一个函数。



我需要这样做的原因是因为我想阻止的类型实际上将编译和做一些与通用版本。然而,这不应该是功能的合同的一部分,可能不是在所有平台/编译器和未来的版本中支持。

解决方案

我会在你的函数调用中使用一个静态assert来创建在函数实例化期间正常失败:

  template< typename T& 
class is_double {static const int value = false; }

template<>
class is_double< double> {static const int value = true; }

template< typename T>
T convert(const char * argument){
BOOST_STATIC_ASSERT(!is_double< T> :: value);
//其余代码
}


I would like to define a template function but disallow instantiation with a particular type. Note that in general all types are allowed and the generic template works, I just want to disallow using a few specific types.

For example, in the code below I wish to prevent using double with the template. This doesn't actually prevent the instantiation, but just causes a linker error by not having the function defined.

template<typename T>
T convert( char const * in )
{ return T(); }

//this way creates a linker error
template<>
double convert<double>( char const * in );

int main()
{
    char const * str = "1234";

    int a = convert<int>( str );
    double b = convert<double>( str );
}

The code is just a demonstration, obviously the convert function must do something more.

Question: In the above code how can I produce a compiler error when trying to use the convert<double> instantiation?


The closest related question I can find is How to intentionally cause a compile-time error on template instantiation It deals with a class, not a function.

The reason I need to do this is because the types I wish to block will actually compile and do something with the generic version. That's however not supposed to be part of the contract of the function and may not be supported on all platforms/compilers and in future versions. Thus I'd like to prevent using it at all.

解决方案

I would use a static assert within your function call to create the proper failure during function instantiation:

template<typename T>
class is_double{ static const int value = false; }

template<>
class is_double<double>{ static const int value = true; }

template<typename T>
T convert( const char *argument ){
    BOOST_STATIC_ASSERT( !is_double<T>::value );
    //rest of code
}

And that should work within a function.

这篇关于禁止特定功能模板实例化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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