gpt4 book ai didi

c++ - 在编译时检测 typedef(模板元编程)

转载 作者:IT老高 更新时间:2023-10-28 23:11:19 30 4
gpt4 key购买 nike

我目前正在做一些模板元编程。就我而言,我可以处理任何“可迭代”类型,即 typedef foo const_iterator 以相同方式存在的任何类型。我试图为此使用新的 C++11 模板元编程,但是我找不到检测某个类型是否丢失的方法。

因为我还需要根据其他特征打开/关闭其他模板特化,所以我目前正在使用带有两个参数的模板,第二个是通过 std::enable_if 生成的。这是我目前正在做的事情:

template <typename T, typename Enable = void>
struct Foo{}; // default case is invalid

template <typename T>
struct Foo< T, typename std::enable_if<std::is_fundamental<T>::value>::type>{
void do_stuff(){ ... }
};

template<typename T>
struct exists{
static const bool value = true;
};

template<typename T>
struct Foo<T, typename std::enable_if<exists< typename T::const_iterator >::value >::type> {
void do_stuff(){ ... }
};

如果没有 exists 帮助器模板,我无法做这样的事情。例如简单地做

template<typename T>
struct Foo<T, typename T::const_iterator> {
void do_stuff(){ ... }
};

没有用,因为在应该使用这种特殊化的情况下,无效的默认情况被实例化了。

但是我在新的 C++11 标准中的任何地方都找不到这个 exists,据我所知,它只是从 boost::type_traits 中获取的种东西。然而在 homepage对于 boost::type_traits 没有显示任何可以替代使用的引用。

是否缺少此功能,或者我是否忽略了其他一些明显的方法来实现所需的行为?

最佳答案

如果您只是想要给定类型是否包含 const_iterator,那么以下是您的代码的简化版本:

template<typename T>
struct void_ { typedef void type; };

template<typename T, typename = void>
struct Foo {};

template<typename T>
struct Foo <T, typename void_<typename T::const_iterator>::type> {
void do_stuff(){ ... }
};

this answer有关此技术如何工作的一些解释。

关于c++ - 在编译时检测 typedef(模板元编程),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7834226/

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