【发布时间】:2015-12-12 01:38:32
【问题描述】:
给定
class A {
public:
bool foo(int) const {return true;}
};
我想要HasFooWithStringReturnTypeAndIsConst<A>::value 和
HasFooWithBoolReturnTypeAndIsNotConst<A>::value 为假(HasFooWithBoolReturnTypeAndIsConst<A>::value 已经返回真,所以工作正常)。这是我所拥有的:
#include <iostream>
#include <type_traits>
#include <string>
class A {
public:
bool foo(int) const {return true;}
};
template <typename...> struct voider {using type = void;};
template <typename... Ts>
using void_t = typename voider<Ts...>::type;
template <typename T, typename = void_t<T>>
struct HasFooWithBoolReturnTypeAndIsNotConst : std::false_type {};
template <typename T>
struct HasFooWithBoolReturnTypeAndIsNotConst<T,
void_t<decltype(std::declval<T&>().foo(std::declval<int>()))>> {
using Foo = bool (T::*)(int);
template <typename U> static std::true_type test (Foo*);
template <typename U> static std::false_type test (...);
static constexpr bool value = std::is_same<decltype(test<T>(nullptr)), std::true_type>::value;
};
template <typename T, typename = void_t<T>>
struct HasFooWithStringReturnTypeAndIsConst : std::false_type {};
template <typename T>
struct HasFooWithStringReturnTypeAndIsConst<T,
void_t<decltype(std::declval<T&>().foo(std::declval<int>()))>> {
using Foo = std::string (T::*)(int) const;
template <typename U> static std::true_type test (Foo*);
template <typename U> static std::false_type test (...);
static constexpr bool value = std::is_same<decltype(test<T>(nullptr)), std::true_type>::value;
};
int main() {
std::cout << HasFooWithStringReturnTypeAndIsConst<A>::value << '\n'; // true (should be false!)
std::cout << HasFooWithBoolReturnTypeAndIsNotConst<A>::value << '\n'; // true (should be false!)
}
谁能解释他们为什么返回true 而不是false?如何修复它们以使它们返回错误? A::foo(int) 是一个返回 bool 的 const 函数,所以它们应该返回 false,不是吗?
【问题讨论】:
标签: c++ templates c++11 template-meta-programming