相关疑难解决方法(0)

基于布尔模板参数启用方法

我想基于布尔模板参数实现一个私有函数.像这样的东西:

#include <iostream>

using namespace std;

template <bool is_enabled = true>
class Aggregator {
public:
    void fun(int a) {
        funInternal(a);
    }

private:
    void funInternal(int a, typename std::enable_if<is_enabled>::type* = 0) {
        std::cout << "Feature is enabled!" << std::endl;
    }

    void funInternal(int a, typename std::enable_if<!is_enabled>::type* = 0) {
        std::cout << "Feature is disabled!" << std::endl;
    }
};

int main()
{
   Aggregator<true> a1;
   Aggregator<false> a2;

   a1.fun(5);
   a2.fun(5);

   return 0;
}
Run Code Online (Sandbox Code Playgroud)

但是上面的程序没有编译:错误:'struct std :: enable_if'中没有名为'type'的类型void funInternal(int a,typename std :: enable_if :: type*= 0).

是否有可能通过enable_if实现所需的行为?

c++ templates enable-if

7
推荐指数
1
解决办法
4374
查看次数

enable_if:没有参数的void成员函数的最小示例

我试图std::enable_if在C++ 11中更好地理解并且一直在尝试编写一个最小的例子:一个A具有成员函数的类,void foo()它具有基于T类模板中的类型的不同实现.
下面的代码给出了期望的结果,但我还没有完全理解它.为什么版本V2有效,但不是V1?为什么U需要"冗余"类型?

#include <iostream>
#include <type_traits>

template <typename T>
class A {

    public:

        A(T x) : a_(x) {}

        // Enable this function if T == int
        /* V1 */ // template <           typename std::enable_if<std::is_same<T,int>::value,int>::type = 0>
        /* V2 */ template <typename U=T, typename std::enable_if<std::is_same<U,int>::value,int>::type = 0>
        void foo() { std::cout << "\nINT: " << a_ << "\n"; }

        // Enable this function if T …
Run Code Online (Sandbox Code Playgroud)

c++ void sfinae enable-if c++11

6
推荐指数
1
解决办法
1820
查看次数

SFINAE:检测成员变量的存在不适用于g ++

我正在尝试结合此答案中用于检测类是否具有成员变量的方法,x并根据此答案选择不同的实现enable_if

基本上,我想编写一个trait类,给定一个type T,它可以访问成员(T::x如果存在),否则提供一个默认值。

以下代码无法在g ++上编译:(Compiler Explorer

#include <iostream>
#include <type_traits>

// classes with / without x member
struct WithX { static constexpr int x = 42; };
struct WithoutX {};

// trait to detect x
template <typename T, typename = void>
struct HasX : std::false_type { };

template <typename T>
struct HasX <T, decltype((void) T::x)> : std::true_type { };

// trait to provide default for x
template …
Run Code Online (Sandbox Code Playgroud)

c++ g++ sfinae

5
推荐指数
1
解决办法
134
查看次数

标签 统计

c++ ×3

enable-if ×2

sfinae ×2

c++11 ×1

g++ ×1

templates ×1

void ×1