gpt4 book ai didi

c++ - SFINAE 的问题

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:17:23 25 4
gpt4 key购买 nike

为什么这段代码(M 类中的 fnc 值)没有被 SFINAE 规则解析?我收到一个错误:

Error   1   error C2039: 'type' : is not a member of
'std::tr1::enable_if<_Test,_Type>'

当然 type 不是成员,它没有在这个通用版本的 enable_if 中定义,但是如果 bool 为真则启用这个版本的 fnc 并且如果它为假则不实例化它背后的整个想法不是吗?有人可以给我解释一下吗?

#include <iostream>
#include <type_traits>

using namespace std;

template <class Ex> struct Null;
template <class Ex> struct Throw;

template <template <class> class Policy> struct IsThrow;

template <> struct IsThrow<Null> {
enum {value = 0};
};

template <> struct IsThrow<Throw> {
enum {value = 1};
};

template <template <class> class Derived>
struct PolicyBase {
enum {value = IsThrow<Derived>::value};
};

template<class Ex>
struct Null : PolicyBase<Null> { };

template<class Ex>
struct Throw : PolicyBase<Throw> { } ;

template<template< class> class SomePolicy>
struct M {

//template<class T>
//struct D : SomePolicy<D<T>>
//{
//};
static const int ist = SomePolicy<int>::value;
typename std::enable_if<ist, void>::type value() const
{
cout << "Enabled";
}

typename std::enable_if<!ist, void>::type value() const
{
cout << "Disabled";
}
};

int main()
{
M<Null> m;
m.value();
}

最佳答案

SFINAE 不适用于非模板函数。相反,您可以例如使用(类的)特化或基于重载的调度:

template<template< class> class SomePolicy>
struct M
{
static const int ist = SomePolicy<int>::value;
void value() const {
inner_value(std::integral_constant<bool,!!ist>());
}
private:
void inner_value(std::true_type) const { cout << "Enabled"; }
void inner_value(std::false_type) const { cout << "Disabled"; }
};

关于c++ - SFINAE 的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4164750/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com