exit-b
exit-b

Reputation: 35

Type inference for integral template parameter

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?

Upvotes: 3

Views: 88

Answers (1)

Guillaume Racicot
Guillaume Racicot

Reputation: 41780

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>;

Upvotes: 4

Related Questions