Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
124 views
in Technique[技术] by (71.8m points)

c++ - How to detect a pointer to an arithmetic type using type traits and concepts?

How do I write a concept that detects a pointer to an arithmetic type?

template <typename T>
concept arithmetic = std::is_arithmetic<T>::value;

template <typename T>
concept pointer_to_arithmetic = requires (T a) {
    { *a } -> arithmetic;
};

template <typename T>
void fn() {
    printf("fail
");
}   

template <pointer_to_arithmetic T>
void fn() {
    printf("pass
");
}   

struct s{};

int main() {
    fn<int>();
    fn<int*>();
    fn<s>();
    fn<s*>();
}

I tried the above and it compiles but doesn't do what it's supposed to.

Expected output is:

fail
pass
fail
fail

Instead I get:

fail
fail
fail
fail

It also doesn't work if I replace *a with a[0].

question from:https://stackoverflow.com/questions/65864208/how-to-detect-a-pointer-to-an-arithmetic-type-using-type-traits-and-concepts

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

For an expression E in a compound requirement, the type constraint predicate is fed decltype((E))1.

decltype encodes the value category of the expression in the type it deduces. Since *p is an lvalue expression. The deduced type is T& for some T.

So you may want to rewrite your pair of concepts as

template <typename T>
concept arithmetic_ref = std::is_arithmetic<std::remove_reference_t<T>>::value;

template <typename T>
concept pointer_to_arithmetic = requires (T a) {
    { *a } -> arithmetic_ref ;
};

The atomic predicate could probably be better named.


Of course, this leaves a couple of questions open. Are you just duck-typing, and so any pointer-like type (even std::optional has operator*) is permissible? Or are you after only fundamental pointer types? How should the concept treat cv-qualified types (it currently doesn't permit them)?

Depending on how you answer those questions, the concept could be tweaked further.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...