问题
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