Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Enforce template type through static_assert

I'm trying to understand the usefulness of static_assert, and I want to know if it can help me in enforcing a design, and if so, how.

I have a general template class that hides its own implementation inside another template class which is partially specialized based on the size of the template type. Here's a brief outline of this design:

template <class T, size_t S = sizeof(T)>
struct Helper;

template <class T>
struct Helper<T, sizeof(long)>
{
    static T bar();
};

// ... other specializations ...

template <class T>
class Foo
{
public:

    T bar()
    {
        return Helper<T>::bar();
    }
};

Foo is only supported if size of T is supported by a specialization of Helper. For example, Foo<long> and Foo<unsigned long> are both supported. However, suppose the user tries to construct a Foo<bool>. Normally, this would generate errors because the specialization of Helper for bool isn't defined, which is intended behaviour.

Is there any way to use static_assert in this design to provide more helpful errors to the user of this interface?

Additionally, I'd like to also restric the user from using a specific type, even though the size might be correct. For example, Foo<float> shouldn't be allowed. Right now, the only way I know of enforcing this is through a bold comment in the documentation. :)

like image 892
Zeenobit Avatar asked Jul 16 '13 14:07

Zeenobit


People also ask

How do I restrict a template type in C++?

There are ways to restrict the types you can use inside a template you write by using specific typedefs inside your template. This will ensure that the compilation of the template specialisation for a type that does not include that particular typedef will fail, so you can selectively support/not support certain types.

How do you use static assert?

The C++ 11 standard introduced a feature named static_assert() which can be used to test a software assertion at the compile time. Syntax: static_assert( constant_expression, string_literal ); Parameters: constant_expression: An integral constant expression that can be converted to a Boolean.

What is template type parameter?

A template parameter is a special kind of parameter that can be used to pass a type as argument: just like regular function parameters can be used to pass values to a function, template parameters allow to pass also types to a function.

Can a template be a template parameter?

A template argument for a template template parameter is the name of a class template. When the compiler tries to find a template to match the template template argument, it only considers primary class templates. (A primary template is the template that is being specialized.)


3 Answers

If it can only work for a specialization of the template class, then have the default template class raise a static assert:

template <class T, size_t S = sizeof(T)>
struct Helper
{
   static_assert(sizeof(T) == -1, "You have to have a specialization for Helper!" );
}

The default template class will only be chosen if there isn't a better specialization, therefore the assert will be risen.

You can use the same technique to disallow types, but you'll need another template parameter that will be used for the static assert check.

template <class T, class G = T, size_t S = sizeof(T)>
struct Helper
{
   static_assert(sizeof(G) == -1, "You have to have a specialization for Helper!" );
}

template <class G>
struct Helper<float,G>
{
   static_assert(sizeof(G) == -1, "You can't use float !" );
}

template <>
struct Helper<int>
{
 //This is a good specialization
};

Then you can try it with these variables:

Helper<bool> a;  //"You have to have a specialization for Helper!"
Helper<float> b; //"You can't use float !"
Helper<int> c;   //compiles OK
like image 133
Yochai Timmer Avatar answered Oct 19 '22 13:10

Yochai Timmer


http://en.cppreference.com/w/cpp/header/type_traits

std::is_base_of and std::is_convertible could help with your first issue and as for the second,

static_assert(!std::is_same<float,T>(),"type can't be float");

hopefully this helps someone else who stumbles upon this question, assuming OP probably found an answer in the 4 years since it was asked :)

like image 12
Austin_Anderson Avatar answered Oct 19 '22 11:10

Austin_Anderson


I figured out a better solution for this problem by combining the answers and comments here.

I can define a static type checker like so:

template <class A, class B>
struct CheckTypes
{
    static const bool value = false;
};

template <class A>
struct CheckTypes<A, A>
{
    static const bool value = true;
};

Not sure if such a struct already exists in the standard library. Anyways, then in Foo, I can check for types and sizes using:

static_assert((sizeof(T) == sizeof(long) || sizeof(T) == sizeof(int)) && !CheckTypes<T, float>::value, "Error!");
like image 1
Zeenobit Avatar answered Oct 19 '22 13:10

Zeenobit