假设您有一系列与类型无关的类,通过返回一个值的给定方法来实现一个公共概念:
class A { public: int val() const { ... } };
class B { public: int val() const { ... } };
假设您需要一个泛型自由函数,它接受一个T
,为任何类型返回一个常规值,而不是实现val
方法,或者为所有具有该值的类型调用val
方法:
template<class T> int val_of(const T& t) { return 0; }
template<class T> int val_of(const T& t) { return t.val(); }
考虑A和B仅仅是示例:您不知道将存在多少实现val
的类型,以及将存在多少不实现它的类型(因此显式专门化将无法扩展)。
根据C++标准,有没有一种简单的方法来静态选择val_of
版本?
我在考虑std::conditional
或std::enable_if
,但我没有找到一种简单的方式来表达条件。
发布于 2014-01-30 06:47:47
只是一个有点长的评论...你的问题已经回答了。但我最近遇到了一个类似的问题。假设您想要编写一个将字符串打印到cout
的方法:使用成员函数write(std::cout)
,如果不可用,则使用自由函数to_string()
,如果不可用,则回退到operator<<
。您可以使用答案中的表达式SFINAE和一些类层次结构来消除重载的歧义:
struct S3 {};
struct S2 : S3 {};
struct S1 : S2 {};
template <class T>
auto print(S1, T const& t) -> decltype(t.write(std::cout)) {
t.write(std::cout);
}
template <class T>
auto print(S2, T const& t) -> decltype(std::cout << to_string(t)) {
std::cout << to_string(t);
}
template <class T>
void print(S3, T const& t) {
std::cout << t;
}
template <class T>
void print(T const& t) {
print(S1(), t);
}
发布于 2014-01-30 04:24:13
您可以使用return-type SFINAE:
template<typename T>
auto val_of(const T& t) -> decltype(std::declval<T>().val())
{
return t.val();
}
int val_of(...)
{
return 0;
}
发布于 2014-01-30 04:44:04
使用此类型特征类来确定类型是否具有val
成员函数。
template<typename U>
struct has_val {
typedef char yes;
typedef struct { char c[2]; } no;
template<typename X>
static constexpr auto test(int) -> decltype( std::declval<X>().val(), yes() );
template<typename X>
static constexpr no test(...);
static constexpr bool value = sizeof(test<U>(0)) == sizeof(yes);
};
您可以将其用作enable_if
的条件。
https://stackoverflow.com/questions/21441803
复制相似问题