使用SFINAE与GCC一起使用但不与Clang一起使用的代码

时间:2016-07-19 18:08:51

标签: c++ c++11 g++ sfinae clang++

我试图在C ++ 11中使用SFINAE来实现序列化库。我的代码适用于GCC但不适用于Clang。我已将其缩减为最小代码:

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编译时没有错误。但是,Clang给了我以下内容:

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

发生了什么以及如何让它与两个编译器一起使用?

1 个答案:

答案 0 :(得分:1)

这看起来像讨论HERE

时的Clang问题

另一个解决方法是使用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;
};

并使用它:

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