调用自由函数而不是方法,如果它不存在 [英] Calling a free function instead of a method if it doesn't exist

查看:272
本文介绍了调用自由函数而不是方法,如果它不存在的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设您有一个类型无关的类家族通过返回值的给定方法实现了一个共同的概念:

Suppose you have a family of type-unrelated classes implementing a common concept by means of a given method returning a value:

class A { public: int val() const { ... } };
class B { public: int val() const { ... } };

假设您需要一个通用的自由函数,它使用 T 为所有类型返回一个常规值,不管类型如何实现 val 方法或调用 val 有一个:

suppose you need a generic free function taking a T returning a conventional value for whatever type NOT implementing the val method or calling the val method for ALL the types that has one:

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 ,以及有多少类型将存在没有实现它(因此显式专门化不会扩展)。

Consider that A and B are just samples: you don't know how many types will ever exist implementing val, and how many types will exist not implementing it (hence explicit specialization won't scale).

是否有一种简单的方法,基于C ++标准,来静态选择 val_of 版本?

Is there a simple way, based on the C++ standards, to come to a way to statically select the val_of version?

我想到 std :: conditional std :: enable_if ,但我没有找到一个简单的方法来表达这个条件。

I was thinking to a std::conditional or std::enable_if, but I didn't find a simple way to express the condition.

推荐答案

...您的问题已经得到解答。但我最近有一个类似的问题。假设你想写一个方法来打印字符串到 cout :使用成员函数 write(std :: cout)如果不可用,则使用自由函数 to_string(),如果不可用则返回到运算符<< 。你可以在回答和一个类层次结构中使用表达式SFINAE来消除重载:

Just a somewhat longer comment... Your question has been answered. But I recently had a similar problem. Say you want to write a method to print strings to cout: Use member function write(std::cout), if not available use free function to_string(), if not available fallback to operator<<. You can use expression SFINAE as in the answer and a little class hierarchy to disambiguate the overloads:

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

这篇关于调用自由函数而不是方法,如果它不存在的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆