Code using SFINAE working with GCC but not with Clang

拈花ヽ惹草 提交于 2021-02-10 05:12:52

问题


I'm trying to use SFINAE in C++11 to implement a serialization library. My code works fine with GCC but not with Clang. I've reduced it here to a minimal code:

template <typename A, typename T>
constexpr auto has_save_method(A& ar, T& t) -> decltype(t.save(ar), bool()) {
        return true;
}

template<class A, typename T, bool has_save>
struct saver;

template<class A, typename T>
struct saver<A,T,true> {
        static void apply(A& ar, T& t) {
                t.save(ar);
        }
};

class MyClass {

        public:

        template<typename A>
        void save(A& ar) {
                // Save the instance in the archive
        }
};

class MyArchive {};

template<typename A, typename T>
void save_to_archive(A& ar, T& t) {
        saver<A,T,has_save_method(ar,t)>::apply(ar,t);
}

int main(int argc, char** argv) {
        MyClass x;
        MyArchive a;
        save_to_archive(a,x);
        return 0;
}

GCC compiles this without error. Clang, however, gives me the following:

test.cpp:30:28: error: non-type template argument is not a constant expression
         saver<A,T,has_save_method(ar,t)>::apply(ar,t);
                                   ^ 
test.cpp:36:2: note: in instantiation of function template specialization
       'save_to_archive<MyArchive, MyClass>' requested here
         save_to_archive(a,x);
         ^

What is happening and how can I make it work with both compilers?


回答1:


This looks like a Clang issue as discussed HERE

Another solution to do it is using void_t trick :

template <typename... T>
using void_t = void;

template <typename A, typename T, typename = void_t<>>
struct has_save_method {
  constexpr static bool value = false;
};

template <typename A, typename T>
struct has_save_method<A, T, void_t<decltype(std::declval<T&>().save(std::declval<A&>()))>> {
  constexpr static bool value = true;
};

And use it like:

template<typename A, typename T>
void save_to_archive(A& ar, T& t) {
        saver<A,T,has_save_method<A, T>::value>::apply(ar,t);
}


来源:https://stackoverflow.com/questions/38465615/code-using-sfinae-working-with-gcc-but-not-with-clang

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!