C++ SFINAE 示例?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/982808/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 18:13:57  来源:igfitidea点击:

C++ SFINAE examples?

c++templatesmetaprogrammingsfinae

提问by rlbond

I want to get into more template meta-programming. I know that SFINAE stands for "substitution failure is not an error." But can someone show me a good use for SFINAE?

我想进入更多模板元编程。我知道 SFINAE 代表“替换失败不是错误”。但是有人可以告诉我 SFINAE 的一个很好的用途吗?

采纳答案by Greg Rogers

Heres one example (from here):

这是一个示例(来自此处):

template<typename T>
class IsClassT {
  private:
    typedef char One;
    typedef struct { char a[2]; } Two;
    template<typename C> static One test(int C::*);
    // Will be chosen if T is anything except a class.
    template<typename C> static Two test(...);
  public:
    enum { Yes = sizeof(IsClassT<T>::test<T>(0)) == 1 };
    enum { No = !Yes };
};

When IsClassT<int>::Yesis evaluated, 0 cannot be converted to int int::*because int is not a class, so it can't have a member pointer. If SFINAE didn't exist, then you would get a compiler error, something like '0 cannot be converted to member pointer for non-class type int'. Instead, it just uses the ...form which returns Two, and thus evaluates to false, int is not a class type.

IsClassT<int>::Yes进行评价时,0不能被转换到int int::*因为int是不是类,因此它不能有一个成员的指针。如果 SFINAE 不存在,那么您将收到编译器错误,例如“0 无法转换为非类类型 int 的成员指针”。相反,它只是使用...返回两个的形式,因此计算结果为 false,int 不是类类型。

回答by Johannes Schaub - litb

I like using SFINAEto check boolean conditions.

我喜欢SFINAE用来检查布尔条件。

template<int I> void div(char(*)[I % 2 == 0] = 0) {
    /* this is taken when I is even */
}

template<int I> void div(char(*)[I % 2 == 1] = 0) {
    /* this is taken when I is odd */
}

It can be quite useful. For example, i used it to check whether an initializer list collected using operator comma is no longer than a fixed size

它可能非常有用。例如,我用它来检查使用运算符逗号收集的初始化列表是否不超过固定大小

template<int N>
struct Vector {
    template<int M> 
    Vector(MyInitList<M> const& i, char(*)[M <= N] = 0) { /* ... */ }
}

The list is only accepted when M is smaller than N, which means that the initializer list has not too many elements.

该列表仅在 M 小于 N 时被接受,这意味着初始化列表没有太多元素。

The syntax char(*)[C]means: Pointer to an array with element type char and size C. If Cis false (0 here), then we get the invalid type char(*)[0], pointer to a zero sized array: SFINAE makes it so that the template will be ignored then.

语法char(*)[C]表示:指向元素类型为 char 和 size 的数组的指针C。如果C为 false(此处为 0),则我们将获得无效类型char(*)[0],指向零大小数组的指针:SFINAE 使得模板将被忽略。

Expressed with boost::enable_if, that looks like this

用 表示boost::enable_if,看起来像这样

template<int N>
struct Vector {
    template<int M> 
    Vector(MyInitList<M> const& i, 
           typename enable_if_c<(M <= N)>::type* = 0) { /* ... */ }
}

In practice, i often find the ability to check conditions a useful ability.

在实践中,我经常发现检查条件的能力是一种有用的能力。

回答by odinthenerd

In C++11 SFINAE tests have become much prettier. Here are a few examples of common uses:

在 C++11 中,SFINAE 测试变得更漂亮了。以下是一些常见用途的示例:

Pick a function overload depending on traits

根据特征选择函数重载

template<typename T>
std::enable_if_t<std::is_integral<T>::value> f(T t){
    //integral version
}
template<typename T>
std::enable_if_t<std::is_floating_point<T>::value> f(T t){
    //floating point version
}

Using a so called type sink idiom you can do pretty arbitrary tests on a type like checking if it has a member and if that member is of a certain type

使用所谓的类型接收器习语,您可以对类型进行相当随意的测试,例如检查它是否有成员以及该成员是否属于某种类型

//this goes in some header so you can use it everywhere
template<typename T>
struct TypeSink{
    using Type = void;
};
template<typename T>
using TypeSinkT = typename TypeSink<T>::Type;

//use case
template<typename T, typename=void>
struct HasBarOfTypeInt : std::false_type{};
template<typename T>
struct HasBarOfTypeInt<T, TypeSinkT<decltype(std::declval<T&>().*(&T::bar))>> :
    std::is_same<typename std::decay<decltype(std::declval<T&>().*(&T::bar))>::type,int>{};


struct S{
   int bar;
};
struct K{

};

template<typename T, typename = TypeSinkT<decltype(&T::bar)>>
void print(T){
    std::cout << "has bar" << std::endl;
}
void print(...){
    std::cout << "no bar" << std::endl;
}

int main(){
    print(S{});
    print(K{});
    std::cout << "bar is int: " << HasBarOfTypeInt<S>::value << std::endl;
}

Here is a live example: http://ideone.com/dHhyHEI also recently wrote a whole section on SFINAE and tag dispatch in my blog (shameless plug but relevant) http://metaporky.blogspot.de/2014/08/part-7-static-dispatch-function.html

这是一个活生生的例子:http: //ideone.com/dHhyHE我最近还在我的博客中写了一个关于 SFINAE 和标签调度的完整部分(无耻的插件但相关)http://metaporky.blogspot.de/2014/08/ part-7-static-dispatch-function.html

Note as of C++14 there is a std::void_t which is essentially the same as my TypeSink here.

请注意,从 C++14 开始,有一个 std::void_t 与此处的 TypeSink 基本相同。

回答by David Joyner

Boost's enable_iflibrary offers a nice clean interface for using SFINAE. One of my favorite usage examples is in the Boost.Iteratorlibrary. SFINAE is used to enable iterator type conversions.

Boost 的enable_if库为使用 SFINAE 提供了一个漂亮干净的界面。我最喜欢的用法示例之一是在Boost.Iterator库中。SFINAE 用于启用迭代器类型转换。

回答by akim

C++17 will probably provide a generic means to query for features. See N4502for details, but as a self-contained example consider the following.

C++17 可能会提供一种查询特性的通用方法。有关详细信息,请参阅N4502,但作为独立示例,请考虑以下内容。

This part is the constant part, put it in a header.

这部分是常量部分,放在标题中。

// See http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2015/n4502.pdf.
template <typename...>
using void_t = void;

// Primary template handles all types not supporting the operation.
template <typename, template <typename> class, typename = void_t<>>
struct detect : std::false_type {};

// Specialization recognizes/validates only types supporting the archetype.
template <typename T, template <typename> class Op>
struct detect<T, Op, void_t<Op<T>>> : std::true_type {};

The following example, taken from N4502, shows the usage:

以下示例取自N4502,显示了用法:

// Archetypal expression for assignment operation.
template <typename T>
using assign_t = decltype(std::declval<T&>() = std::declval<T const &>())

// Trait corresponding to that archetype.
template <typename T>
using is_assignable = detect<T, assign_t>;

Compared to the other implementations, this one is fairly simple: a reduced set of tools (void_tand detect) suffices. Besides, it was reported (see N4502) that it is measurably more efficient (compile-time and compiler memory consumption) than previous approaches.

与其他实现相比,这个实现相当简单:一组减少的工具 (void_tdetect) 就足够了。此外,据报道(参见N4502),它比以前的方法更有效(编译时和编译器内存消耗)。

Here is a live example, which includes portability tweaks for GCC pre 5.1.

这是一个实时示例,其中包括针对 GCC 5.1 之前的可移植性调整。

回答by zangw

Here is one good article of SFINAE: An introduction to C++'s SFINAE concept: compile-time introspection of a class member.

这是 SFINAE 的一篇好文章:C++ 的 SFINAE 概念介绍:类成员的编译时自省

Summary it as following:

总结如下:

/*
 The compiler will try this overload since it's less generic than the variadic.
 T will be replace by int which gives us void f(const int& t, int::iterator* b = nullptr);
 int doesn't have an iterator sub-type, but the compiler doesn't throw a bunch of errors.
 It simply tries the next overload. 
*/
template <typename T> void f(const T& t, typename T::iterator* it = nullptr) { }

// The sink-hole.
void f(...) { }

f(1); // Calls void f(...) { }


template<bool B, class T = void> // Default template version.
struct enable_if {}; // This struct doesn't define "type" and the substitution will fail if you try to access it.

template<class T> // A specialisation used if the expression is true. 
struct enable_if<true, T> { typedef T type; }; // This struct do have a "type" and won't fail on access.

template <class T> typename enable_if<hasSerialize<T>::value, std::string>::type serialize(const T& obj)
{
    return obj.serialize();
}

template <class T> typename enable_if<!hasSerialize<T>::value, std::string>::type serialize(const T& obj)
{
    return to_string(obj);
}


declvalis an utility that gives you a "fake reference" to an object of a type that couldn't be easily construct. declvalis really handy for our SFINAE constructions.

declval是一个实用程序,它为您提供对无法轻松构造的类型的对象的“假引用”。declval对于我们的 SFINAE 结构来说真的很方便。

struct Default {
    int foo() const {return 1;}
};

struct NonDefault {
    NonDefault(const NonDefault&) {}
    int foo() const {return 1;}
};

int main()
{
    decltype(Default().foo()) n1 = 1; // int n1
//  decltype(NonDefault().foo()) n2 = n1; // error: no default constructor
    decltype(std::declval<NonDefault>().foo()) n2 = n1; // int n2
    std::cout << "n2 = " << n2 << '\n';
}

回答by whoan

Here's another (late) SFINAEexample, based on Greg Rogers's answer:

这是另一个(后期)SFINAE示例,基于Greg Rogers回答

template<typename T>
class IsClassT {
    template<typename C> static bool test(int C::*) {return true;}
    template<typename C> static bool test(...) {return false;}
public:
    static bool value;
};

template<typename T>
bool IsClassT<T>::value=IsClassT<T>::test<T>(0);

In this way, you can check the value's value to see whether Tis a class or not:

这样,您可以检查value的值以查看是否T为类:

int main(void) {
    std::cout << IsClassT<std::string>::value << std::endl; // true
    std::cout << IsClassT<int>::value << std::endl;         // false
    return 0;
}

回答by user

Here, I am using template function overloading (not directly SFINAE) to determine whether a pointer is a function or member class pointer: (Is possible to fix the iostream cout/cerr member function pointers being printed as 1 or true?)

在这里,我使用模板函数重载(不是直接 SFINAE)来确定指针是函数还是成员类指针:(是否可以修复 iostream cout/cerr 成员函数指针被打印为 1 或 true?

https://godbolt.org/z/c2NmzR

https://godbolt.org/z/c2NmzR

#include<iostream>

template<typename Return, typename... Args>
constexpr bool is_function_pointer(Return(*pointer)(Args...)) {
    return true;
}

template<typename Return, typename ClassType, typename... Args>
constexpr bool is_function_pointer(Return(ClassType::*pointer)(Args...)) {
    return true;
}

template<typename... Args>
constexpr bool is_function_pointer(Args...) {
    return false;
}

struct test_debugger { void var() {} };
void fun_void_void(){};
void fun_void_double(double d){};
double fun_double_double(double d){return d;}

int main(void) {
    int* var;

    std::cout << std::boolalpha;
    std::cout << "0. " << is_function_pointer(var) << std::endl;
    std::cout << "1. " << is_function_pointer(fun_void_void) << std::endl;
    std::cout << "2. " << is_function_pointer(fun_void_double) << std::endl;
    std::cout << "3. " << is_function_pointer(fun_double_double) << std::endl;
    std::cout << "4. " << is_function_pointer(&test_debugger::var) << std::endl;
    return 0;
}

Prints

印刷

0. false
1. true
2. true
3. true
4. true

As the code is, it could(depending on the compiler "good" will) generate a run time call to a function which will return true or false. If you would like to force the is_function_pointer(var)to evaluate at compile type (no function calls performed at run time), you can use the constexprvariable trick:

正如代码一样,它可以(取决于编译器的“好”意愿)生成对将返回 true 或 false 的函数的运行时调用。如果您想强制is_function_pointer(var)在编译类型(在运行时不执行函数调用)进行评估,您可以使用constexpr变量技巧:

constexpr bool ispointer = is_function_pointer(var);
std::cout << "ispointer " << ispointer << std::endl;

By the C++ standard, all constexprvariables are guaranteed to be evaluated at compile time (Computing length of a C string at compile time. Is this really a constexpr?).

根据 C++ 标准,所有constexpr变量都保证在编译时进行评估(在编译时计算 C 字符串的长度。这真的是 constexpr 吗?)。