Peter VARGA
Peter VARGA

Reputation: 5186

Get underlying type for a template used in decltype

#include <atomic>

std::atomic<int> bar;

auto foo() -> decltype(bar)
{
        return bar++;
}

I receive this gcc error message:

error: use of deleted function ‘std::atomic<int>::atomic(const std::atomic<int>&)’

Changing the type in decltype() to int works. To keep my code more general how can I get the type int as defined between the <>?

Upvotes: 3

Views: 589

Answers (3)

Darklighter
Darklighter

Reputation: 2192

Well, you don’t want to return something the same type as bar…

≥ C++98

template<typename T>
T foo() {
    return bar++;
}

≥ C++11

auto foo() -> decltype(bar++) {
    return bar++;
}

≥ C++14

auto foo() {
    return bar++;
}

Notice how straightforward the C++11 syntax looks when we come from C++14 (although boilerplate).

Upvotes: 2

Edward
Edward

Reputation: 7100

You can do it like this:

auto foo() -> decltype(bar.operator++())
{
    return bar++;
}

Upvotes: 4

Lightness Races in Orbit
Lightness Races in Orbit

Reputation: 385295

Yeah, std::atomic doesn't have a value_type member or anything like that, so this is not "trivial". Well, it is, but sort of not. Meh.

If you're stuck with C++11:

auto foo() -> decltype(bar.load())
{
    return bar++;
}

Since C++14, though, you may simply write:

#include <atomic>

std::atomic<int> bar;

auto foo()
{
    return bar++;
}

Upvotes: 1

Related Questions