gpt4 book ai didi

c++ - 从 enable_if 中的依赖类的 true_type/false_type typedef 获取 bool 值

转载 作者:太空狗 更新时间:2023-10-29 21:06:27 24 4
gpt4 key购买 nike

我有课

template <typename T>
struct Trait { typedef std::false_type IsGood; };

template <>
struct Trait<int> { typedef std::true_type IsGood; };

这样的调用无法在 MSVC 2010 上编译

template <typename T, typename Enable = void> class Foo;

template <typename T>
class Foo <T, std::enable_if<typename Trait<T>::IsGood::value>::type>
{};

// This fails as well
template <typename T>
class Foo <T, typename std::enable_if<Trait<T>::IsGood::value>::type>
{};

// And this fails horribly
template <typename T>
class Foo <T, typename std::enable_if<typename Trait<T>::IsGood::value>::type>
{};

同时

template <typename T>
class Foo <T, typename std::enable_if<std::is_same<std::true_type,
typename Trait<T>::IsGood>::value>::type>
{};

有效——为什么?

错误信息是:

main.cpp(12): error C2039: 'type' : is not a member of 'std::tr1::enable_if<_Test>'
with
[
_Test=false
]
main.cpp(12): error C2146: syntax error : missing ',' before identifier 'type'
main.cpp(12): error C2065: 'type' : undeclared identifier
main.cpp(13): error C2976: 'Foo' : too few template arguments

最佳答案

您正在使用 typename在错误的地方。这是正确的:

template <typename T>
class Foo <T, typename std::enable_if<Trait<T>::IsGood::value>::type>
{}; // ^^^^^^^ here should be typename

现在编译正常:http://ideone.com/0SwO9

但您正在使用 typename作为:

template <typename T>
class Foo <T, std::enable_if<typename Trait<T>::IsGood::value>::type>
{}; //^^^^^^^ wrong place

Trait<T>::IsGood::value不是类型,所以你不能申请typename在上面。

GCC 错误信息非常清楚:

prog.cpp:12:62: error: type/value mismatch at argument 1 in template parameter list for 'template<bool <anonymous>, class _Tp> struct std::enable_if'

看看你自己:http://ideone.com/9ujJv

关于c++ - 从 enable_if 中的依赖类的 true_type/false_type typedef 获取 bool 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7689334/

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