Name lookup issue, GCC and clang disagree [duplicate]
Asked Answered
T

1

8

As pointed out by ecatmur, this question already has an answer here.

This question is obviously not a duplicate of trailing return type using decltype with a variadic template function. It actually tries to propose a simpler solution to address the issue in that thread. The question is whether this solution is correct according to the standard, because GCC and clang disagree on it. Just read the question a little more carefully, and you will realize that.

This question is inspired by this one. I'm trying to come up with a simpler solution than the ones already provided, and end up with this:

#include <iostream>

struct S {
    template <typename T>
    static T sum(T t){
        return t;
    }

    template <typename T, typename ...U>
    static auto sum(T t, U... u) -> decltype(t + sum(u...)) {
        return t + sum(u...);
    }
};

int main() {
    std::cout << S::sum(1, 1.5, 2) << '\n';
}

While this solution works with GCC, it does not solve the problem at all on clang. So, I'm wondering which one is correct.

Talbott answered 8/5, 2015 at 9:19 Comment(4)
fails to compile for me on clang: main.cpp:10:17: note: candidate template ignored: substitution failure [with T = int, U = <double, int>]: no matching function for call to 'sum' static auto sum(T t, U... u) -> decltype(t + sum(u...)) { ^ ~~~ main.cpp:5:17: note: candidate function template not viable: requires single argument 't', but 3 arguments were provided static auto sum(T t){Glennisglennon
@ecatmur This is not a duplicate. Just read my question a little more carefully and you will realize that.Talbott
@ecatmur You're right. Gonna close this question.Talbott
@ecatmur Since the question already has an answer. Deleting seems inappropriate. But I have edited the question to mention the other thread.Talbott
M
0

Best workaround I came up is:

#include <iostream>

struct S {
    template <typename T>
    static T sum(T t){
        return t;
    }

    template <typename S, typename T>
    static auto sum(S s, T t) -> decltype(s + t) {
        return s + t;
    }

    template <typename S, typename T, typename ...U>
    static auto sum(S s, T t, U... u) -> decltype(s + t) {
        return s + sum(t, u...);
    }
};

int main() {
    std::cout << S::sum(1, 1.5, 2) << '\n';
}

clang seems to have a problem with resolving recursive function/method in decltype directive...

Monteria answered 8/5, 2015 at 10:2 Comment(2)
decltype(s + t) may be different from decltype(s + x) where x = t + u....Talbott
you're seem to be right - I saw it is working on the simple example of yours... let me rethink my answer then...Monteria

© 2022 - 2024 — McMap. All rights reserved.