user2209008
user2209008

Reputation:

Template parameter type deduction

I'm fiddling around with template meta-programming again and trying to get a better understanding of it. I've created the following trivial template meta-function.

template<typename T, T Value>
struct is_positive
{
    static const bool value = (Value >= 0);
}

const bool is_positive_test_1 = is_positive<int32_t, 3>::value;  //true
const bool is_positive_test_2 = is_positive<int32_t, 0>::value;  //true
const bool is_positive_test_3 = is_positive<int32_t, -1>::value; //false

Everything works fine, as expected, but I want to know if there is a way that I can eliminate the need to specify the type of the Value parameter, so the calling convention would instead be:

is_positive<1>::value

Thank you in advance. :)

EDIT

I would like this to not just work for int32_t, but also float32_t and any other numeric type. For example, I want is_positive<3.141f>::value to be valid without needing to specialize the template.

Upvotes: 2

Views: 377

Answers (2)

Nick Louloudakis
Nick Louloudakis

Reputation: 6005

One good trick is to give the first argument a default value in case not any is given for it:

template<typename T=int32_t, T Value>

So that you have:

template<typename T=int32_t, T Value>
struct is_positive
{
    static const bool value = (Value >= 0);
}

const bool is_positive_test_1 = is_positive<3>::value;  //true
const bool is_positive_test_2 = is_positive<0>::value;  //true
const bool is_positive_test_3 = is_positive<-1>::value; //false

Reference: http://www.cplusplus.com/doc/tutorial/templates/

UPDATE:

It seems that you are additionally searching for an automatic way of variable type decision. My mind goes to dynamic typing (meaning that the type of the argument is recognized at runtime and not on compile-time).Many languages use dynamic typing (such as PHP and Python) but C++ is a static typing language, meaning that you have to declare the type of your variable (for example int i = 0;) and this type will be set for the variable at compile time. Therefore, what you are asking for can not be done automatically in C++.

Upvotes: 0

David Brown
David Brown

Reputation: 13526

Only function template parameters can be deduced, not class template parameters. In C++03 you can't have compile time functions, but in C++11 you can using constexpr:

template<typename T>
constexpr bool is_positive(T val) {
    return val >= 0;
}

And just to show that it is evaluated at compile time, the following will compile:

template<bool V>
struct compile_time_tester
{};

int main() {
    compile_time_tester<is_positive(3.14)> foo;
    return 0;
}

Upvotes: 3

Related Questions