Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Type inference for integral template parameter

Tags:

c++

c++11

c++14

I have created a type that holds a unique identity of a method

template <typename Method, Method method>
struct identity {
};

So I can describe methods in a distinctive way, even if they have the same signature

struct Class {
    void foo() {}
    void bar() {}
};

typedef identity<decltype(&Class::foo), &Class::foo> foo_identity;
typedef identity<decltype(&Class::bar), &Class::bar> bar_identity;

std::cout << std::boolalpha << std::is_same<foo_identity, bar_identity>::value << std::end;
// prints "false"

Since the method of instantiation the identity is too verbose, as both names are used twice, it can be shortened with:

#define GEN_IDENTITY(NAME) identity<decltype(&NAME), &NAME>
GEN_IDENTITY(Class::foo)

But is there a way to deduce it without the use of a macro? Or maybe there is some other way to get a type that distinctively describes a method?

like image 781
exit-b Avatar asked Mar 02 '26 20:03

exit-b


1 Answers

But is there a way to deduce it without the use of a macro?

At the moment, no. There's a proposal for adding a construct in the language that will make non type template argument deductible just like auto (N4469)

But for now, you can simplify identity with that instead:

template<typename T, T t>
using identity = std::integral_constant<T, t>;
like image 102
Guillaume Racicot Avatar answered Mar 05 '26 11:03

Guillaume Racicot



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!