开发者

C++0x Function delete - Delete all but certain types

开发者 https://www.devze.com 2023-03-10 07:10 出处:网络
In C++0开发者_如何学Gox, I can do something like this: double f(double x) { return x; } template<class T>

In C++0开发者_如何学Gox, I can do something like this:

double f(double x) { return x; }
template<class T>
  T f(T x) = delete;

To prevent f() from being called on any other type than double.

What I'm trying to do is similar, however, not quite the same.

I have a function that operates on pointer arrays. For example:

template<class T>
  T* some_string_function(T* x);

I want to be able to make T work for char, char16_t, and char32_t, but not any other type. I was thinking that C++0x's delete would be a good way to accomplish this. Basically, I want to be able to prevent this function from working with any type that isn't one of the three Unicode char types, but I still want to have the benefits of function templates, which allow me to generalise types and avoid repeating code.

What would be the best way to solve this problem? Is it possible?


Use boost::enable_if, along with type traits.

template<class T>
T* some_string_function(T* x, boost::enable_if<is_char_type<T>);

(assuming is_char_type is a type trait you define, which evaluates to true for the desired types, and false for all others)


You could do it using type_traits:

template<typename T>
typename enable_if<is_same<char, T>::value || is_same<char16_t, T>::value || is_same<char32_t, T>::value, T*>::type some_string_function(T *x)
{
    return x;
}

Though you'd have to specifically specify const as well if you want to allow that.


I think the best way to do it is using a combination of static_assert and is_same (Both C++0x features). This also allows for a more friendly error message when you make an invalid call to the function.

#include <iostream>
using namespace std;

template<typename T> T* f(T*)
{
    static_assert
    (is_same<T, char>::value
     || is_same<T, char16_t>::value
     || is_same<T, char32_t>::value,
     "Invalid Type, only char pointers allowed");
}

int main()
{
    cout<<*f(new char('c'));//Compiles
    cout<<*f(new int(3));//Error
}
0

精彩评论

暂无评论...
验证码 换一张
取 消