相关疑难解决方法(0)

使用enable_if选择类构造函数

考虑以下代码:

#include <iostream>
#include <type_traits>

template <typename T>
struct A {
    int val = 0;

    template <class = typename std::enable_if<T::value>::type>
    A(int n) : val(n) {};
    A(...) { }

    /* ... */
};

struct YES { constexpr static bool value = true; };
struct NO { constexpr static bool value = false; };

int main() {
    A<YES> y(10);
    A<NO> n;
    std::cout << "YES: " << y.val << std::endl
              << "NO:  " << n.val << std::endl;
}
Run Code Online (Sandbox Code Playgroud)

我想有选择地使用enable_if为某些类型定义构造函数A :: A(int).对于所有其他类型,都有默认构造函数A :: A(...),当替换失败时,它应该是编译器的默认情况.然而这对我来说有意义编译器(gcc版本4.9.0 …

c++ templates constructor sfinae

47
推荐指数
3
解决办法
2万
查看次数

标签 统计

c++ ×1

constructor ×1

sfinae ×1

templates ×1